示例#1
0
 def _settings_export_to_file_button_fired(self):
     """Exports current gui settings to INI file. Prompts user for file name and location.
     Should handle all expected error cases.  Defaults to file "config.ini" in the swift_path
     """
     # Prompt user for location and name of file
     file = FileDialog(action='save as',
                       default_directory=swift_path,
                       default_filename='config.ini',
                       wildcard='*.ini')
     is_ok = file.open()
     if is_ok == OK:
         print('Exporting settings to local path {0}'.format(file.path))
         # copy settings so we can modify dict in place to write for configparser
         settings_out = {}
         # iterate over nested dict and set inner value to a bare string rather than dict
         for section in self.settings:
             settings_out[section] = {}
             for setting, inner_dict in self.settings[section].iteritems():
                 settings_out[section][setting] = str(inner_dict.value)
         # write out with config parser
         parser = configparser.RawConfigParser()
         # the optionxform is needed to handle case sensitive settings
         parser.optionxform = str
         parser.read_dict(settings_out)
         # write to ini file
         try:
             with open(file.path, "w") as f:
                 parser.write(f)
         except IOError as e:
             print('Unable to export settings to file due to IOError: {}'.
                   format(e))
     else:  # No error message because user pressed cancel and didn't choose a file
         pass
示例#2
0
 def open(self):
     """ Shows a dialog to open a file.
     """
     logger.debug('PythonShellTask: opening file')
     dialog = FileDialog(parent=self.window.control, wildcard='*.py')
     if dialog.open() == OK:
         self._open_file(dialog.path)
示例#3
0
    def _save_(self, type_='pic', path=None):
        """
        """
        if path is None:
            dlg = FileDialog(action='save as',
                             default_directory=os.path.expanduser('~'))
            if dlg.open() == OK:
                path = dlg.path
                self.status_text = 'Image Saved: %s' % path

        if path is not None:
            if type_ == 'pdf' or path.endswith('.pdf'):
                self._render_to_pdf(filename=path)
            else:
                # auto add an extension to the filename if not present
                # extension is necessary for PIL compression
                # set default save type_ DEFAULT_IMAGE_EXT='.png'

                # see http://infohost.nmt.edu/tcc/help/pubs/pil/formats.html
                saved = False
                for ei in IMAGE_EXTENSIONS:
                    if path.endswith(ei):
                        self._render_to_pic(path)
                        saved = True
                        break

                if not saved:
                    self._render_to_pic(add_extension(path, DEFAULT_IMAGE_EXT))
示例#4
0
def popup_save(parent=None):
    """Popup a dialog asking for an image name to save the scene to.
    This is used mainly to save a scene in full screen mode. Returns a
    filename, returns empty string if action was cancelled. `parent` is
    the parent widget over which the dialog will be popped up.
    """
    from pyface.api import FileDialog, OK

    extensions = [
        '*.png', '*.jpg', '*.tiff', '*.bmp', '*.ps', '*.eps', '*.pdf', '*.tex',
        '*.rib', '*.wrl', '*.oogl', '*.vrml', '*.obj', '*.iv', '*.pov', '*.x3d'
    ]
    descriptions = [
        "PNG", "JPG", "TIFF", "Bitmap", "PostScript", "EPS", "PDF", "Tex",
        "RIB", "WRL", "Geomview", "VRML", "Wavefront", "Open Inventor",
        "Povray", "X3D"
    ]
    wildcard = ""
    for description, extension in zip(descriptions, extensions):
        wildcard += "{} ({})|{}|".format(description, extension, extension)
    wildcard += "Determine by extension (*.*)|(*.*)"

    dialog = FileDialog(parent=parent,
                        title='Save scene to image',
                        action='save as',
                        default_filename="snapshot.png",
                        wildcard=wildcard)
    if dialog.open() == OK:
        return dialog.path
    else:
        return ''
示例#5
0
文件: controller.py 项目: vnoel/vl3
 def save(self, ui_info):
     print self.view.save_image_file
     fd = FileDialog(action='save as', default_path=self.view.save_image_file)
     if fd.open() == OK:
         print 'Saving figure to ', fd.path
         self.view.save_image(fd.path)
         self.view.save_image_file = fd.path
示例#6
0
def open_outputdbs():
    """Open file"""
    wildcard = "Output files (*.dbx;*.exo)|*.dbx;*.exo|"
    dialog = FileDialog(action="open files", wildcard=wildcard)
    if dialog.open() != pyOK:
        return []
    return dialog.paths
示例#7
0
def OpenFileDialog(action, wildcard, self):
    from pyface.api import FileDialog, OK
    doaction = action
    if action == "new":
        doaction = "save as"
    dialog = FileDialog(action=doaction, wildcard=wildcard)
    dialog.open()
    if dialog.return_code == OK:
        self.filedir = dialog.directory
        self.filename = dialog.filename
        self.Configuration_File = os.path.join(dialog.directory,
                                               dialog.filename)
        if action == "open":
            self._config = load_config(dialog.path, self.config_class)
            self._config.configure_traits(view=self.config_view())
            self.saved = False
            self.config_changed = True
        if action == "new":
            self._config = self.config_class()
            self._config.configure_traits(view=self.config_view())
            self._save_to_file()
            self.saved = False
            self.config_changed = True
        if action == "save as":
            self._save_to_file()
            self.saved = True
            self.config_changed = False
示例#8
0
 def perform(self,event):
     """Perform the Save Phantom  Action """
     wildcard = 'MagicalPhantom files (*.mp)|*.mp|' + FileDialog.WILDCARD_ALL
     parent = self.window.control
     dialog = FileDialog(parent=parent,
                         title = 'Open MagicalPhantom file',
                         action = 'open',wildcard = wildcard)
     if dialog.open()==OK:
         if not isfile(dialog.path):
             error("File '%s' does not exist"%dialog.path,parent)
             return
    
     run_manager = self.window.application.get_service('mphantom.api.RunManager')
     
     phantom = run_manager.model
     
    
     
     print dialog.path
             
     phantom.clear_phantom()
     phantom.load_phantom(dialog.path)
     
    
     
     self.window.active_perspective = self.window.perspectives[1]
示例#9
0
 def _save_button_fired(self):
     f = FileDialog(
         action='save as',
         wildcard=
         'ASCII data (*.dat;*.txt)|*.dat;*.txt|Binary data (*.npy)|*.npy|')
     if f.open() == OK:
         self.save_data(f.path)
示例#10
0
    def on_savedata(self):
        """ Handles the user requesting that 
            the data of the function is to be saved.
        """
        import os
        dlg = FileDialog(parent=self.control,
                         title='Export function data',
                         default_directory=os.getcwd(),
                         default_filename="", wildcard='*.csv',
                         action='save as')
        if dlg.open() == OK:
            path = dlg.path

            print "Saving data to", path, "..."
            try:

                #                factory  = self.factory
                #                plotitem = factory.plotitem
                #                x_values = getattr(self.object, plotitem.index)
                #                y_values = getattr(self.object, plotitem.value)
                x_values = self.value.xdata
                y_values = self.value.ydata
                np.savetxt(path, np.vstack((x_values, y_values)).transpose())
            except:
                print "Error saving!"
                raise
            print "Plot saved."
        return
示例#11
0
    def perform(self, event):
        """ Performs the action. """

        extensions = [
            '*.png', '*.jpg', '*.jpeg', '*.tiff', '*.bmp', '*.ps', '*.eps',
            '*.tex', '*.rib', '*.wrl', '*.oogl', '*.pdf', '*.vrml', '*.obj',
            '*.iv', '*.pov', '*x3d'
        ]

        descriptions = [
            'PNG', 'JPG', 'JPEG', 'TIFF', 'Bitmap', 'PostScript', 'EPS', 'TeX',
            'RIB', 'WRL', 'Geomview', 'PDF', 'VRML', 'Wavefront', 'Povray',
            'X3D'
        ]

        wildcard = ''

        for description, extension in zip(descriptions, extensions):
            wildcard += '{} ({})|{}|'.format(description, extension, extension)

        wildcard += 'Determine by extension (*.*)|(*.*)'

        dialog = FileDialog(parent=self.window.control,
                            title='Save scene to image',
                            action='save as',
                            wildcard=wildcard)
        if dialog.open() == OK:
            scene = self.scene_manager.current_scene
            if scene is not None:
                scene.save(dialog.path)

        return
示例#12
0
    def _do_convert_fired(self):

        dialog = FileDialog(action='open files',
                            wildcard=(FileDialog.create_wildcard(
                                "FCS files", "*.fcs")))  #@UndefinedVariable
        if dialog.open() == OK:
            self.model.input_files = dialog.paths
示例#13
0
    def parse_autoupdate(self):
        '''
        '''

        f = FileDialog(
            action='open',
            #                       default_directory=paths.modeling_data_dir
            default_directory=self.data_directory)
        if f.open() == OK:
            self.info('loading autoupdate file {}'.format(f.path))

            # open a autoupdate config dialog
            from clovera_configs import AutoUpdateParseConfig
            adlg = AutoUpdateParseConfig('', '')
            info = adlg.edit_traits()
            if info.result:
                self.info('tempoffset = {} (C), timeoffset = {} (min)'.format(
                    adlg.tempoffset, adlg.timeoffset))
                rids = self.data_loader.load_autoupdate(
                    f.path, adlg.tempoffset, adlg.timeoffset)
                auto_files = True
                if auto_files:
                    for rid in rids:
                        root = f.path + '_data'
                        with open(os.path.join(root, rid, 'samples.lst'),
                                  'w') as s:
                            s.write('{}'.format(rid))

                        self.execute_files(rid=rid, root=root, block=True)
示例#14
0
 def load_config_file(self, ui_info):
     dialog = FileDialog(action="open", wildcard="*.ini")
     dialog.open()
     if dialog.return_code == OK:
         if dialog.path != ui_info.ui.context["object"].project_info.config_file:
             shutil.copy(dialog.path, ui_info.ui.context["object"].project_info.config_file)
         load_config(self.pipeline, ui_info.ui.context["object"].project_info.config_file)
示例#15
0
文件: gui.py 项目: NicolasRannou/cmp
 def _save_fired(self):
     import pickle
     import os.path
     # support the new traits api
     try:
       import apptools.sweet_pickle as sp        
     except ImportError:
       import enthought.sweet_pickle as sp 
     
     # support the new traits api
     try:
       from pyface.api import FileDialog, OK
     except ImportError: 
       from enthought.pyface.api import FileDialog, OK
     
     wildcard = "CMP Configuration State (*.pkl)|*.pkl|" \
                     "All files (*.*)|*.*"
     dlg = FileDialog(wildcard=wildcard,title="Filename to store configuration state",\
                      resizeable=False, action = 'save as', \
                      default_directory=self.subject_workingdir,)
     
     if dlg.open() == OK:
         if not dlg.path.endswith('.pkl'):
             dlg.path = dlg.path + '.pkl'
         self.save_state(dlg.path)
示例#16
0
 def _file_dialog_(self, action, **kw):
     '''
     '''
     #         print 'file_dialog', kw
     dlg = FileDialog(action=action, **kw)
     if dlg.open() == OK:
         return dlg.path
示例#17
0
 def _export_off_changed(self):
     fd = FileDialog(title='Export OFF',
                     action='save as',
                     wildcard='OFF Meshes|*.off')
     if fd.open() == OK:
         v = all_verts[self.visible][self.animator.current_frame]
         save_off(fd.path, v, tris)
示例#18
0
 def do_load_cfg(self, info):
     """Read in the pickled configuration."""
     the_pybert = info.object
     dlg = FileDialog(action="open",
                      wildcard="*.pybert_cfg",
                      default_path=the_pybert.cfg_file)
     if dlg.open() == OK:
         try:
             with open(dlg.path, "rb") as the_file:
                 the_PyBertCfg = pickle.load(the_file)
             if not isinstance(the_PyBertCfg, PyBertCfg):
                 raise Exception(
                     "The data structure read in is NOT of type: PyBertCfg!"
                 )
             for prop, value in vars(the_PyBertCfg).items():
                 if prop == "tx_taps":
                     for count, (enabled, val) in enumerate(value):
                         setattr(the_pybert.tx_taps[count], "enabled",
                                 enabled)
                         setattr(the_pybert.tx_taps[count], "value", val)
                 elif prop == "tx_tap_tuners":
                     for count, (enabled, val) in enumerate(value):
                         setattr(the_pybert.tx_tap_tuners[count], "enabled",
                                 enabled)
                         setattr(the_pybert.tx_tap_tuners[count], "value",
                                 val)
                 else:
                     setattr(the_pybert, prop, value)
             the_pybert.cfg_file = dlg.path
         except Exception as err:
             error_message = "The following error occurred:\n\t{}\nThe configuration was NOT loaded.".format(
                 err)
             the_pybert.handle_error(error_message)
示例#19
0
    def on_savedata(self):
        """ Handles the user requesting that 
            the data of the function is to be saved.
        """
        import os
        dlg = FileDialog(parent=self.control,
                         title='Export function data',
                         default_directory=os.getcwd(),
                         default_filename="",
                         wildcard='*.csv',
                         action='save as')
        if dlg.open() == OK:
            path = dlg.path

            print("Saving data to", path, "...")
            try:

                #                factory  = self.factory
                #                plotitem = factory.plotitem
                #                x_values = getattr(self.object, plotitem.index)
                #                y_values = getattr(self.object, plotitem.value)
                x_values = self.value.xdata
                y_values = self.value.ydata
                np.savetxt(path, np.vstack((x_values, y_values)).transpose())
            except:
                print("Error saving!")
                raise
            print("Plot saved.")
        return
示例#20
0
    def on_savedata(self):
        """ Handles the user requesting that the data of the function \
            is to be saved.
        """
        import os
        dlg = FileDialog(parent=self.control,
                         title='Export function data',
                         default_directory=os.getcwd(),
                         default_filename="", wildcard='*.csv',
                         action='save as')
        if dlg.open() == OK:
            path = dlg.path

            print "Saving data to", path, "..."
            try:

                factory = self.factory
                plotitem = factory.plotitem
                x_values = getattr(self.object, plotitem.index)
                y_values = getattr(self.object, plotitem.value_list)

            except:
                print "Error saving!"
                raise
            print "Plot saved."
        return
示例#21
0
文件: task.py 项目: jomason/omnivore
    def prompt_local_file_dialog(self,
                                 title="",
                                 most_recent=True,
                                 save=False,
                                 default_filename="",
                                 wildcard="*"):
        """Display an "open file" dialog to load from the local filesystem,
        defaulting to the most recently used directory.

        If there is no previously used directory, default to the directory of
        the current file.

        Returns the directory path on the filesystem, or None if not found.
        """
        dirpath = ""
        action = "save as" if save else "open"
        if not title:
            title = "Save File" if save else "Open File"
        if self.active_editor:
            # will try path of current file
            dirpath = self.active_editor.best_file_save_dir

        dialog = FileDialog(parent=self.window.control,
                            title=title,
                            default_directory=dirpath,
                            action=action,
                            default_filename=default_filename,
                            wildcard=wildcard)
        if dialog.open() == OK:
            return dialog.path
        return None
示例#22
0
    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
示例#23
0
    def action_save(self, info):
        # First make a copy of the frame we will save
        save_frame = info.object.camera.frame.copy()

        # Then find out where to save it
        dialog = FileDialog(parent=info.ui.control, action="save as", modal=True, title="Save Image")
        try:
            dialog.default_directory = info.object._current_folder
        except TraitError:
            pass  # thrown if _current_folder is None
        dialog.open()
        path = dialog.path

        # Store the directory for the next time
        info.object._current_folder = dialog.directory

        if dialog.return_code != OK:
            return

        # Default is PNG
        if "." not in path:
            path += ".png"

        # Save it
        scipy.misc.imsave(path, save_frame)
示例#24
0
def save_file():
    wildcard='*.txt'
    dialog = FileDialog(title='Select the file to save as...',
        action='save as', wildcard=wildcard)
    if dialog.open() == Pyface_OK:
        return dialog.path
    return ''
示例#25
0
def OpenFileDialog(action, wildcard, self):
    from pyface.api import FileDialog, OK
    doaction = action
    if action == "new":
        doaction = "save as"
    dialog = FileDialog(action=doaction, wildcard=wildcard)
    dialog.open()
    if dialog.return_code == OK:
        self.filedir = dialog.directory
        self.filename = dialog.filename
        self.Configuration_File = os.path.join(dialog.directory, dialog.filename)
        if action == "open":
            self._config = load_config(dialog.path, self.config_class)
            self._config.configure_traits(view=self.config_view())
            self.saved = False
            self.config_changed = True
        if action == "new":
            self._config = self.config_class()
            self._config.configure_traits(view=self.config_view())
            self._save_to_file()
            self.saved = False
            self.config_changed = True
        if action == "save as":
            self._save_to_file()
            self.saved = True
            self.config_changed = False
示例#26
0
    def parse_autoupdate(self):
        """
        """

        f = FileDialog(
            action="open",
            #                       default_directory=paths.modeling_data_dir
            default_directory=self.data_directory,
        )
        if f.open() == OK:
            self.info("loading autoupdate file {}".format(f.path))

            # open a autoupdate config dialog
            from clovera_configs import AutoUpdateParseConfig

            adlg = AutoUpdateParseConfig("", "")
            info = adlg.edit_traits()
            if info.result:
                self.info("tempoffset = {} (C), timeoffset = {} (min)".format(adlg.tempoffset, adlg.timeoffset))
                rids = self.data_loader.load_autoupdate(f.path, adlg.tempoffset, adlg.timeoffset)
                auto_files = True
                if auto_files:
                    for rid in rids:
                        root = f.path + "_data"
                        with open(os.path.join(root, rid, "samples.lst"), "w") as s:
                            s.write("{}".format(rid))

                        self.execute_files(rid=rid, root=root, block=True)
示例#27
0
文件: utils.py 项目: enthought/mayavi
def popup_save(parent=None):
    """Popup a dialog asking for an image name to save the scene to.
    This is used mainly to save a scene in full screen mode. Returns a
    filename, returns empty string if action was cancelled. `parent` is
    the parent widget over which the dialog will be popped up.
    """
    from pyface.api import FileDialog, OK

    extensions = ['*.png', '*.jpg', '*.tiff', '*.bmp', '*.ps',
                  '*.eps', '*.pdf', '*.tex', '*.rib', '*.wrl',
                  '*.oogl', '*.vrml', '*.obj', '*.iv', '*.pov',
                  '*.x3d']
    descriptions = ["PNG", "JPG", "TIFF", "Bitmap", "PostScript",
                    "EPS", "PDF", "Tex", "RIB", "WRL",
                    "Geomview", "VRML", "Wavefront", "Open Inventor",
                    "Povray", "X3D"]
    wildcard = ""
    for description, extension in zip(descriptions, extensions):
        wildcard += "{} ({})|{}|".format(description,
                                         extension,
                                         extension)
    wildcard += "Determine by extension (*.*)|(*.*)"

    dialog = FileDialog(
        parent=parent, title='Save scene to image',
        action='save as', default_filename="snapshot.png",
        wildcard=wildcard
    )
    if dialog.open() == OK:
        return dialog.path
    else:
        return ''
示例#28
0
    def on_open(self):
        """ 
        Shows a dialog to open a file.
        """

        if self.model.modified:
            ret = confirm(
                parent=None,
                message=
                "Are you sure you want to discard the current workflow?",
                title="Clear workflow?")

            if ret != YES:
                return

        dialog = FileDialog(
            parent=self.window.control,
            action='open',
            wildcard=(
                FileDialog.create_wildcard("Cytoflow workflow", "*.flow") +
                ';' +  #@UndefinedVariable  
                FileDialog.create_wildcard("All files",
                                           "*")))  #@UndefinedVariable
        if dialog.open() == OK:
            self.open_file(dialog.path)
            self.filename = dialog.path
            self.window.title = "Cytoflow - " + self.filename
示例#29
0
def load_instance(path, wildcard):
    fd = FileDialog(action='open', default_directory=path, wildcard=wildcard)
    if fd.open() == OK and fd.path <> '':
        with open(fd.path, 'rb') as infile:
            return pickle.load(infile)
    else:
        return None
示例#30
0
    def perform(self, event):
        """ Performs the action. """
        mv = get_imayavi(self.window)
        s = get_scene(mv)
        if s is None:
            return

        wildcard = 'All files (*.*)|*.*'
        for src in registry.sources:
            if len(src.extensions) > 0:
                if wildcard.endswith('|') or \
                   src.wildcard.startswith('|'):
                    wildcard += src.wildcard
                else:
                    wildcard += '|' + src.wildcard

        parent = self.window.control
        dialog = FileDialog(parent=parent,
                            title='Open supported data file',
                            action='open',
                            wildcard=wildcard)
        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist!" % dialog.path, parent)
                return
            # FIXME: Ask for user input if a filetype is unknown and
            # choose appropriate reader.
            src = mv.open(dialog.path)
            if src is not None:
                mv.engine.current_selection = src
示例#31
0
    def on_export(self):
        """
        Shows a dialog to export a file
        """

        information(
            None, "This will save exactly what you see on the screen "
            "to a file.", "Export")

        f = ""
        filetypes_groups = self.plot_pane.canvas.get_supported_filetypes_grouped(
        )
        filename_exts = []
        for name, ext in filetypes_groups.iteritems():
            if f:
                f += ";"
            f += FileDialog.create_wildcard(name,
                                            " ".join(["*." + e for e in ext
                                                      ]))  #@UndefinedVariable
            filename_exts.append(ext)

        dialog = FileDialog(parent=self.window.control,
                            action='save as',
                            wildcard=f)

        if dialog.open() == OK:
            filetypes = self.plot_pane.canvas.get_supported_filetypes().keys()
            if not filter(lambda ext: dialog.path.endswith(ext),
                          ["." + ext for ext in filetypes]):
                selected_exts = filename_exts[dialog.wildcard_index]
                ext = sorted(selected_exts, key=len)[0]
                dialog.path += "."
                dialog.path += ext

            self.plot_pane.export(dialog.path)
示例#32
0
文件: sources.py 项目: PerryZh/mayavi
    def perform(self, event):
        """ Performs the action. """
        mv = get_imayavi(self.window)
        s = get_scene(mv)
        if s is None:
            return

        wildcard = 'All files (*.*)|*.*'
        for src in registry.sources:
            if len(src.extensions) > 0:
                if wildcard.endswith('|') or \
                   src.wildcard.startswith('|'):
                       wildcard += src.wildcard
                else:
                    wildcard += '|' + src.wildcard

        parent = self.window.control
        dialog = FileDialog(parent=parent,
                            title='Open supported data file',
                            action='open', wildcard=wildcard
                            )
        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist!"%dialog.path, parent)
                return
            # FIXME: Ask for user input if a filetype is unknown and
            # choose appropriate reader.
            src = mv.open(dialog.path)
            if src is not None:
                mv.engine.current_selection = src
示例#33
0
    def perform(self, event):

        plot_component = self.container.component

        filter = 'PNG file (*.png)|*.png|\nTIFF file (*.tiff)|*.tiff|'
        dialog = FileDialog(action='save as', wildcard=filter)

        if dialog.open() != OK:
            return

        # Remove the toolbar before saving the plot, so the output doesn't
        # include the toolbar.
        plot_component.remove_toolbar()

        filename = dialog.path

        width, height = plot_component.outer_bounds

        gc = PlotGraphicsContext((width, height), dpi=72)
        gc.render_component(plot_component)
        try:
            gc.save(filename)
        except KeyError as e:
            errmsg = ("The filename must have an extension that matches "
                      "a graphics format, such as '.png' or '.tiff'.")
            if str(e.message) != '':
                errmsg = ("Unknown filename extension: '%s'\n" %
                          str(e.message)) + errmsg

            error(None, errmsg, title="Invalid Filename Extension")

        # Restore the toolbar.
        plot_component.add_toolbar()
示例#34
0
def open_outputdbs():
    """Open file"""
    wildcard = 'Output files (*.dbx;*.exo)|*.dbx;*.exo|'
    dialog = FileDialog(action="open files", wildcard=wildcard)
    if dialog.open() != pyOK:
        return []
    return dialog.paths
示例#35
0
    def _save_as_fired(self):
        # create raw
        try:
            raw = self.model.get_raw()
        except Exception as err:
            error(None, str(err), "Error Creating KIT Raw")
            raise

        # find default path
        stem, _ = os.path.splitext(self.sqd_file)
        if not stem.endswith('raw'):
            stem += '-raw'
        default_path = stem + '.fif'

        # save as dialog
        dlg = FileDialog(action="save as",
                         wildcard="fiff raw file (*.fif)|*.fif",
                         default_path=default_path)
        dlg.open()
        if dlg.return_code != OK:
            return

        fname = dlg.path
        if not fname.endswith('.fif'):
            fname += '.fif'
            if os.path.exists(fname):
                answer = confirm(None, "The file %r already exists. Should it "
                                 "be replaced?", "Overwrite File?")
                if answer != YES:
                    return

        self.queue.put((raw, fname))
        self.queue_len += 1
示例#36
0
    def perform(self, event):
        """ Performs the action. """
        wildcard = 'Python files (*.py)|*.py'
        parent = self.window.control
        dialog = FileDialog(parent=parent,
                            title='Open Python file',
                            action='open',
                            wildcard=wildcard)
        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist" % dialog.path, parent)
                return

            # Get the globals.
            # The following code is taken from scripts/mayavi2.py.
            g = sys.modules['__main__'].__dict__
            if 'mayavi' not in g:
                mv = get_imayavi(self.window)
                g['mayavi'] = mv
                g['engine'] = mv.engine
            g['__file__'] = dialog.path
            # Do execfile
            try:
                # If we don't pass globals twice we get NameErrors and nope,
                # using exec open(script_name).read() does not fix it.
                exec(compile(open(dialog.path).read(), dialog.path, 'exec'), g,
                     g)
            except Exception as msg:
                exception(str(msg))
示例#37
0
    def export_chaco_python(self, info):
        """Implements the "File / Export / Chaco python code" menu item."""

        dialog = FileDialog(
            parent=info.ui.control,
            default_filename=info.object.name + ".py",
            action="save as",
            title="Chaco python file",
        )
        if dialog.open() == OK:
            # The data is attached to the function as an attribute.  This
            # will allow a program to import a module, look for functions in
            # the module that have the _colormap_data attribute and recover
            # the data without having to call the function.
            f = open(dialog.path, "w")
            f.write("\n")
            f.write("from enthought.chaco.api import ColorMapper\n\n")
            f.write("def %s(range, **traits):\n" % info.object.name)
            f.write('    """Generator for the colormap "%s"."""\n' % info.object.name)
            f.write(
                ("    return ColorMapper.from_segment_map(" "%s._colormap_data, range=range, **traits)\n\n")
                % info.object.name
            )
            f.write("%s._colormap_data = " % info.object.name)
            segment_map = info.object.colormap_editor._segment_map()
            seg_code = "%r" % segment_map
            seg_code = seg_code.replace("'red'", "\n        'red'")
            seg_code = seg_code.replace("'green'", "\n        'green'")
            seg_code = seg_code.replace("'blue'", "\n        'blue'")
            seg_code = seg_code.replace("}", "\n        }")
            f.write(seg_code)
            f.close()
示例#38
0
def get_file_list_from_dialog():
    dlg = FileDialog(title='Choose files',
                     action='open files',
                     wildcard=xye_wildcard)
    if dlg.open() == OK:
        return dlg.paths
    return []
示例#39
0
    def _save_snapshot(self):
        """Invoked by the toolbar menu to save a snapshot of the scene
        to an image.  Note that the extension of the filename
        determines what image type is saved.  The default is PNG.
        """
        if self._panel is not None:
            extensions = ['*.png', '*.jpg', '*.tiff', '*.bmp', '*.ps',
                          '*.eps', '*.pdf', '*.tex', '*.rib', '*.wrl',
                          '*.oogl', '*.vrml', '*.obj', '*.iv', '*.pov',
                          '*.x3d']

            descriptions = ["PNG", "JPG", "TIFF", "Bitmap", "PostScript",
                            "EPS", "PDF", "Tex", "RIB", "WRL",
                            "Geomview", "VRML", "Wavefront", "Open Inventor",
                            "Povray", "X3D"]

            for description, extension in zip(descriptions, extensions):
                wildcard += "{} ({})|{}|".format(description,
                                                 extension,
                                                 extension)
            wildcard += "Determine by extension (*.*)|(*.*)"

            dialog = FileDialog(
                parent = self._panel,
                title = 'Save scene to image',
                action = 'save as',
                default_filename = "snapshot.png",
                wildcard = wildcard
            )
            if dialog.open() == OK:
                # The extension of the path will determine the actual
                # image type saved.
                self.save(dialog.path)
示例#40
0
    def _save_as_fired(self):
        # create raw
        try:
            raw = self.model.get_raw()
        except Exception as err:
            error(None, str(err), "Error Creating KIT Raw")
            raise

        # find default path
        stem, _ = os.path.splitext(self.sqd_file)
        if not stem.endswith('raw'):
            stem += '-raw'
        default_path = stem + '.fif'

        # save as dialog
        dlg = FileDialog(action="save as",
                         wildcard="fiff raw file (*.fif)|*.fif",
                         default_path=default_path)
        dlg.open()
        if dlg.return_code != OK:
            return

        fname = dlg.path
        if not fname.endswith('.fif'):
            fname += '.fif'
            if os.path.exists(fname):
                answer = confirm(
                    None, "The file %r already exists. Should it "
                    "be replaced?", "Overwrite File?")
                if answer != YES:
                    return

        self.queue.put((raw, fname))
        self.queue_len += 1
示例#41
0
def get_transformed_filename(filename):
    dialog = FileDialog(default_path=filename, action="save as", title="Save as", wildcard=xye_wildcard)
    if dialog.open() == OK:
        filename = dialog.path
        if filename:
            return filename
    return None
示例#42
0
    def parse_autoupdate(self):
        '''
        '''

        f = FileDialog(action='open',
#                       default_directory=paths.modeling_data_dir
                       default_directory=self.data_directory
                       )
        if f.open() == OK:
            self.info('loading autoupdate file {}'.format(f.path))

            # open a autoupdate config dialog
            from clovera_configs import AutoUpdateParseConfig
            adlg = AutoUpdateParseConfig('', '')
            info = adlg.edit_traits()
            if info.result:
                self.info('tempoffset = {} (C), timeoffset = {} (min)'.format(adlg.tempoffset, adlg.timeoffset))
                rids = self.data_loader.load_autoupdate(f.path, adlg.tempoffset, adlg.timeoffset)
                auto_files = True
                if auto_files:
                    for rid in rids:
                        root = f.path + '_data'
                        with open(os.path.join(root, rid, 'samples.lst'), 'w') as s:
                            s.write('{}'.format(rid))

                        self.execute_files(rid=rid, root=root,
                                           block=True)
def resize_and_save_matplotlib_figure(figure):        
    ''' To save a matplotlib figure with custom width and height in pixels 
    requires changing the bounding box while is being rendered! '''
   
    # get figure size
    figure_size = MatplotlibFigureSize(figure=figure)
    old_dpi = figure_size.dpi
    old_width_inches = figure_size.width_inches
    old_height_inches = figure_size.height_inches
    ui = figure_size.edit_traits(kind='modal')
    widget = ui.control
    # maybe change figure size
    if ui.result:
        figure.dpi = figure_size.dpi # set new dpi
        figure.bbox_inches.p1 = figure_size.width_inches, figure_size.height_inches # set new width and height in inches
    else:
        return

    # get file name with (correct choice of formats)
    fd = FileDialog(
        action='save as',
        wildcard=FileDialog.create_wildcard('All available formats', ['*.eps', '*.png', '*.pdf', '*.ps', '*.svg']),
    )
    if fd.open() != OK:
        return
    file_name = fd.path
    
    # save it
    figure.savefig(file_name)

    # restore original figure size
    figure.dpi = old_dpi # restore old dpi
    figure.bbox_inches.p1 = old_width_inches, old_height_inches # restore old width and height in inches
示例#44
0
 def save_config_file(self, ui_info):
     dialog = FileDialog(action="save as", default_filename="config.ini")
     dialog.open()
     if dialog.return_code == OK:
         save_config(self.pipeline, ui_info.ui.context["object"].project_info.config_file)
         if dialog.path != ui_info.ui.context["object"].project_info.config_file:
             shutil.copy(ui_info.ui.context["object"].project_info.config_file, dialog.path)
示例#45
0
文件: actions.py 项目: arkyaC/mayavi
    def perform(self, event):
        """ Performs the action. """

        extensions = [
            '*.png', '*.jpg', '*.jpeg', '*.tiff', '*.bmp', '*.ps', '*.eps',
            '*.tex', '*.rib', '*.wrl', '*.oogl', '*.pdf', '*.vrml', '*.obj',
            '*.iv', '*.pov', '*x3d'
        ]

        descriptions = [
            'PNG', 'JPG', 'JPEG', 'TIFF', 'Bitmap', 'PostScript', 'EPS',
            'TeX', 'RIB', 'WRL', 'Geomview', 'PDF', 'VRML', 'Wavefront',
	    'Povray', 'X3D'
        ]

        wildcard = ''

        for description, extension in zip(descriptions, extensions):
            wildcard += '{} ({})|{}|'.format(description, extension, extension)
        
        wildcard += 'Determine by extension (*.*)|(*.*)'

        dialog = FileDialog(
            parent   = self.window.control,
            title    = 'Save scene to image',
            action   = 'save as',
            wildcard = wildcard
        )
        if dialog.open() == OK:
            scene = self.scene_manager.current_scene
            if scene is not None:
                scene.save(dialog.path)

        return
示例#46
0
 def open(self):
     """ Shows a dialog to open a file.
     """
     logger.debug('PythonShellTask: opening file')
     dialog = FileDialog(parent=self.window.control, wildcard='*.py')
     if dialog.open() == OK:
         self._open_file(dialog.path)
示例#47
0
    def _file_dialog_(self, action, **kw):
        '''
        '''
#         print 'file_dialog', kw
        dlg = FileDialog(action=action, **kw)
        if dlg.open() == OK:
            return dlg.path
示例#48
0
    def perform(self, event):
        """ Performs the action. """
        wildcard = 'Python files (*.py)|*.py'
        parent = self.window.control
        dialog = FileDialog(parent=parent,
                            title='Open Python file',
                            action='open', wildcard=wildcard
                            )
        if dialog.open() == OK:
            if not isfile(dialog.path):
                error("File '%s' does not exist"%dialog.path, parent)
                return

            # Get the globals.
            # The following code is taken from scripts/mayavi2.py.
            g = sys.modules['__main__'].__dict__
            if 'mayavi' not in g:
                mv = get_imayavi(self.window)
                g['mayavi'] = mv
                g['engine'] = mv.engine
            # Do execfile
            try:
                # If we don't pass globals twice we get NameErrors and nope,
                # using exec open(script_name).read() does not fix it.
                execfile(dialog.path, g, g)
            except Exception, msg:
                exception(str(msg))
示例#49
0
    def perform(self, event):

        plot_component = self.container.component

        filter = 'PNG file (*.png)|*.png|\nTIFF file (*.tiff)|*.tiff|'
        dialog = FileDialog(action='save as', wildcard=filter)

        if dialog.open() != OK:
            return

        # Remove the toolbar before saving the plot, so the output doesn't
        # include the toolbar.
        plot_component.remove_toolbar()

        filename = dialog.path

        width, height = plot_component.outer_bounds

        gc = PlotGraphicsContext((width, height), dpi=72)
        gc.render_component(plot_component)
        try:
            gc.save(filename)
        except KeyError as e:
            errmsg = ("The filename must have an extension that matches "
                      "a graphics format, such as '.png' or '.tiff'.")
            if str(e.message) != '':
                errmsg = ("Unknown filename extension: '%s'\n" %
                          str(e.message)) + errmsg

            error(None, errmsg, title="Invalid Filename Extension")

        # Restore the toolbar.
        plot_component.add_toolbar()
示例#50
0
 def save_as(self):
     dlg = FileDialog( action='save as', wildcard='*.rep')
     dlg.open()
     if dlg.filename!='':
         fi = file(dlg.filename,'w')
         dump(self,fi)
         fi.close()
示例#51
0
文件: graph.py 项目: jirhiker/pychron
    def _save_(self, type_='pic', path=None):
        """
        """
        if path is None:
            dlg = FileDialog(action='save as')
            if dlg.open() == OK:
                path = dlg.path
                self.status_text = 'Image Saved: %s' % path

        if path is not None:
            if type_ == 'pdf':
                self._render_to_pdf(filename=path)
            else:
                # auto add an extension to the filename if not present
                # extension is necessary for PIL compression
                # set default save type_ DEFAULT_IMAGE_EXT='.png'

                # see http://infohost.nmt.edu/tcc/help/pubs/pil/formats.html
                saved = False
                for ei in IMAGE_EXTENSIONS:
                    if path.endswith(ei):
                        self._render_to_pic(path)
                        saved = True
                        break

                if not saved:
                    self._render_to_pic(path + DEFAULT_IMAGE_EXT)
示例#52
0
 def _savePlot_fired(self):
     dialog = FileDialog(title='Save plot as...', action='save as',
                         wildcard = FileDialog.create_wildcard('Portable Network Graphics', '*.png'))
     if not dialog.open():
         self.add_line("ERROR opening save file.")
         return
     self.plotRU(save=True,filename=dialog.path)
    def export(self):
        dialog = FileDialog(action='save as', title='Export Experiment',
                                wildcard='csv files (*.csv)|*.csv')
        dialog.open()
        path = dialog.path
        if not path.endswith('.csv'):
            path += '.csv'
        with open(path, 'w') as f:
            fieldnames = [
                'well',
                'led',
                'program',
                'program_id',
                'total_steps',
                'step',
                'step_no',
                'step_id',
                'step_start_time',
                'step_duration',
                'step_intensity',
                'step_pulsed',
                'step_pulse_on',
                'step_pulse_off',
                'step_repeat']
            writer = csv.DictWriter(f, fieldnames=fieldnames, restval='None')
            writer.writeheader()

            for well_group in self.plate.well_groups:
                led_row = {'well': well_group.position}
                well = well_group.wells[0]
                for led in well.leds:
                    led_row['led'] = led.name
                    if led.program:
                        program_row = {}
                        program_row['program'] = led.program.name
                        program_row['program_id'] = led.program.ID
                        program_row['total_steps'] = len(led.program.steps)
                        prg_does_repeat = led.program._after_end == 'repeat'
                        program_row.update(led_row)
                        if len(led.program.steps) == 0:
                            # Program has no Steps, write now
                            writer.writerow(program_row)
                        for step_no, step in enumerate(led.program.steps):
                            program_row['step'] = step.name
                            program_row['step_no'] = step_no + 1
                            program_row['step_id'] = step.ID
                            step_start = sum(step.duration for step in led.program.steps[:step_no])
                            program_row['step_start_time'] = step_start
                            program_row['step_duration'] = step.duration
                            program_row['step_intensity'] = step.intensity
                            program_row['step_pulsed'] = ['no', 'yes'][step.is_pulsed]
                            program_row['step_pulse_on'] = step.pulse_on
                            program_row['step_pulse_off'] = step.pulse_off
                            is_last_step = step_no == len(led.program.steps) - 1
                            step_does_repeat = prg_does_repeat and is_last_step
                            program_row['step_repeat'] = ['no', 'yes'][step_does_repeat]
                            writer.writerow(program_row)
                    else:
                        writer.writerow(led_row)
示例#54
0
 def load(self):
     dlg = FileDialog(action='open', wildcard='*.rep')
     dlg.open()
     if dlg.filename != '':
         fi = file(dlg.filename, 'rb')
         s = load(fi)
         self.copy_traits(s)
         fi.close()
示例#55
0
def get_save_as_filename():
    wildcard = 'PNG file (.png)|*.png|TIFF file (.tiff)|*.tiff|EPS file (.eps)|*.eps|SVG file (.svg)|*.svg|'
    dialog = FileDialog(action='save as', title='Save as', wildcard=wildcard)
    if dialog.open() == OK:
        filename = dialog.path
        if filename:
            return filename
    return None
示例#56
0
 def save_schedule(self, uiinfo):
     obj = self._get_schedule_obj(uiinfo)
     f = FileDialog(action='save as',
                    default_path=obj._filename,
                    wildcard='*.sch')
     if f.open() == OK:
         obj._filename = f.path
         write_schedule(obj._filename, obj.get_schedule())
示例#57
0
 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)
示例#58
0
    def on_open_file(self):
        """ Open a new file. """

        if self.control:
            dlg = FileDialog(parent=self.control, wildcard='*.py')

            if dlg.open() == OK:
                self._editor.path = dlg.path
示例#59
0
 def on_save(self):
     """ Shows a dialog to open a file.
     """
     dialog = FileDialog(parent=self.window.control,
                         action='save as',
                         wildcard='*.flow')
     if dialog.open() == OK:
         self.save_file(dialog.path)
示例#60
0
 def _save_new_cal_dir_fired(self):
     dialog = FileDialog(#parent=self.window.control,
                         title='Save calibration directory',
                         action='save as',
                         )
     if dialog.open() == OK:
         alignedR = self.get_aligned_R()
         alignedR.save_to_files_in_new_directory(dialog.path)