Esempio n. 1
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
Esempio n. 2
0
 def tno_confirm_delete(self, node=None):
     """ Confirms that a specified object can be deleted or not.
     """
     return (confirm(
         self.handler.parent,
         "Delete '%s' from the file space?\n\nNote: No files will be "
         "deleted." % self.root.name, 'Delete File Space Root') == YES)
Esempio n. 3
0
 def tno_confirm_delete ( self, node = None ):
     """ Confirms that a specified object can be deleted or not.
     """
     return (confirm( self.handler.parent,
            "Delete '%s' from the file space?\n\nNote: No files will be "
            "deleted." % self.root.name,
            'Delete File Space Root' ) == YES)
Esempio n. 4
0
 def _inner(self, info, *args, **kw):
     if self.object_modified(info):
         mesg = 'This record has been modified. '
         mesg += 'Are you sure you wish to discard the changes?'
         if confirm(info.ui.control, mesg) == NO:
             return False
     return func(self, info, *args, **kw)
Esempio n. 5
0
    def read_cache(self):
        """Read the user cache from persistent storage.  Returns False if
        there was no cache to read."""

        try:
            f = open(self._cache_file, 'r')

            try:
                if confirm(None, "It was not possible to connect to the "
                        "permissions server. Instead you can use the settings "
                        "used when you last logged in from this system. If "
                        "you do this then any changes made to settings "
                        "normally held on the permissions server will be lost "
                        "when you next login successfully.\n\nDo you want to "
                        "use the saved settings?") != YES:
                    raise Exception("")

                try:
                    self.cache = pickle.load(f)
                except:
                    raise Exception("Unable to read %s." % self._cache_file)
            finally:
                f.close()
        except IOError, e:
            if e.errno == errno.ENOENT:
                # There is no cache file.
                return False

            raise Exception("Unable to open %s: %s." % (self._cache_file, e))
Esempio n. 6
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
Esempio n. 7
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
Esempio n. 8
0
    def read_cache(self):
        """Read the user cache from persistent storage.  Returns False if
        there was no cache to read."""

        try:
            f = open(self._cache_file, 'r')

            try:
                if confirm(
                        None, "It was not possible to connect to the "
                        "permissions server. Instead you can use the settings "
                        "used when you last logged in from this system. If "
                        "you do this then any changes made to settings "
                        "normally held on the permissions server will be lost "
                        "when you next login successfully.\n\nDo you want to "
                        "use the saved settings?") != YES:
                    raise Exception("")

                try:
                    self.cache = pickle.load(f)
                except:
                    raise Exception("Unable to read %s." % self._cache_file)
            finally:
                f.close()
        except IOError, e:
            if e.errno == errno.ENOENT:
                # There is no cache file.
                return False

            raise Exception("Unable to open %s: %s." % (self._cache_file, e))
Esempio n. 9
0
    def open_file(self, path):
        f = open(path, 'r')
        unpickler = pickle.Unpickler(f)

        try:
            version = unpickler.load()
        except TraitError:
            error(parent=None,
                  message="This doesn't look like a Cytoflow file. Or maybe "
                  "you tried to load a workflow older than version "
                  "0.5?")
            return

        if version != self.model.version:
            ret = confirm(
                parent=None,
                message="This is Cytoflow {}, but you're trying "
                "to load a workflow from version {}. This may or "
                "may not work!  Are you sure you want to proceed?".format(
                    self.model.version, version),
                title="Load workflow?")
            if ret != YES:
                return

        try:
            new_workflow = unpickler.load()
        except TraitError as e:
            error(parent=None, message="Error trying to load the workflow.")
            return

        # a few things to take care of when reloading
        for wi_idx, wi in enumerate(new_workflow):

            # get wi lock
            wi.lock.acquire()

            # clear the wi status
            wi.status = "loading"

            # re-link the linked list.  i thought this would get taken care
            # of in deserialization, but i guess not...
            if wi_idx > 0:
                wi.previous_wi = new_workflow[wi_idx - 1]

        # replace the current workflow with the one we just loaded

        if False:  # for debugging the loading of things
            from .event_tracer import record_events

            with record_events() as container:
                self.model.workflow = new_workflow

            container.save_to_directory(os.getcwd())
        else:
            self.model.workflow = new_workflow
            self.model.modified = False

        for wi in self.model.workflow:
            wi.lock.release()
Esempio n. 10
0
def display_confirm(message, title=None, cancel=False):
    answer = pyface.confirm(None, message, title=title, cancel=cancel)
    if answer == pyface.YES:
        return True
    if answer == pyface.NO:
        return False
    if answer == pyface.CANCEL:
        return None
Esempio n. 11
0
 def close(self, info, isok):
     # Return True to indicate that it is OK to close the window.
     if not info.object.saved:
         response = confirm(info.ui.control,
                            "Value is not saved.  Are you sure you want to exit?")
         return response == YES
     else:
         return True
Esempio n. 12
0
 def object__delete_changed(self, info):
     if not info.initialized:
         return
     if info.object._selected is not None:
         selected = info.object._selected
         mesg = 'Are you sure you want to delete animal %s?'
         if confirm(info.ui.control, mesg % selected) == YES:
             info.object.animals.remove(selected)
             info.object._selected = None
Esempio n. 13
0
 def _decompress_fired(self):
     ask_again = True
     delete = confirm(None, 'Delete zip-file after decompression was selected.\nDo you want to delete it for all selected tasks?')
     if delete == YES:
         ask_again = False
     for task in self.task_selector.evaluated_tasks:
         task_dir = os.path.join(self.project_info.project_dir, task)
         # results_dir = os.path.join(task_dir, 'results')
         zip_file = os.path.join(task_dir, 'results.zip')
         zf = zipfile.ZipFile(zip_file, 'r')
         zf.extractall(task_dir)
         zf.close()
         if delete and ask_again:
             if confirm(None, 'Delete zip-file after decompression was selected.\nDo you want to delete it?') == YES:
                 os.remove(zip_file)
         elif delete:
             os.remove(zip_file)
     print 'Results decompressed'
Esempio n. 14
0
    def _editor_closing_changed_for_window(self, editor):
        """ Handle the editor being closed.
        """
        if (editor is self) and self.dirty:
            retval = confirm(self.window.control, title="Save Resource",
                message="'%s' has been modified. Save changes?" %
                self.name[1:])

            if retval == YES:
                self.save()
Esempio n. 15
0
 def _generate_fired(self):
     if confirm(None, 'All results will be deleted!') == YES:
         for task_num, task in zip(self.task_num_lst, self.task_name_lst):
             task_dir = os.path.join(self.project_info.project_dir, task)
             prepare_dir(task_dir)
             outfile = open(os.path.join(task_dir, task + '.inp'), 'w')
             if self.n_var_input > 0:
                 self.__insert_vars_to_inp(outfile, self.freet_data[task_num - 1, :])
             outfile.close()
             print 'TASK ' + task + ' created'
Esempio n. 16
0
 def _on_remove_tubes(self):
     conf = confirm(None,
                    "Are you sure you want to remove the selected tube(s)?",
                    "Remove tubes?")
     if conf:
         for (tube, _) in self.model.selected:
             self.model.tubes.remove(tube)
             
     if not self.model.tubes:
         self.model.dummy_experiment = None
Esempio n. 17
0
 def _on_remove_condition(self):
     pass
     col = self.model.selected[0][1]
     if self.model.tubes[0].trait(col).condition == True:
         conf = confirm(
             None,
             "Are you sure you want to remove condition \"{}\"?".format(
                 col), "Remove condition?")
         if conf == YES:
             self._remove_metadata(col)
     else:
         error(None, "Can't remove column {}".format(col), "Error")
Esempio n. 18
0
    def _save_fired(self):
        if self.n_scale_params:
            subjects_dir = self.model.mri.subjects_dir
            subject_from = self.model.mri.subject
            subject_to = self.model.raw_subject or self.model.mri.subject
        else:
            subject_to = self.model.mri.subject

        # ask for target subject
        if self.n_scale_params:
            mridlg = NewMriDialog(subjects_dir=subjects_dir, subject_from=subject_from, subject_to=subject_to)
            ui = mridlg.edit_traits(kind="modal")
            if ui.result != True:
                return
            subject_to = mridlg.subject_to

        # find bem file to run mne_prepare_bem_model
        if self.can_prepare_bem_model and self.prepare_bem_model:
            bem_job = self.model.get_prepare_bem_model_job(subject_to)
        else:
            bem_job = None

        # find trans file destination
        raw_dir = os.path.dirname(self.model.hsp.file)
        trans_file = trans_fname.format(raw_dir=raw_dir, subject=subject_to)
        dlg = FileDialog(action="save as", wildcard=trans_wildcard, default_path=trans_file)
        dlg.open()
        if dlg.return_code != OK:
            return
        trans_file = dlg.path
        if not trans_file.endswith(".fif"):
            trans_file = trans_file + ".fif"
            if os.path.exists(trans_file):
                answer = confirm(None, "The file %r already exists. Should it " "be replaced?", "Overwrite File?")
                if answer != YES:
                    return

        # save the trans file
        try:
            self.model.save_trans(trans_file)
        except Exception as e:
            error(None, str(e), "Error Saving Trans File")
            return

        # save the scaled MRI
        if self.n_scale_params:
            job = self.model.get_scaling_job(subject_to)
            self.queue.put(job)
            self.queue_len += 1

            if bem_job is not None:
                self.queue.put(bem_job)
                self.queue_len += 1
Esempio n. 19
0
 def _compress_fired(self):
     ask_again = True
     delete = confirm(None, 'Delete directory "results" after compression  was selected.\nDo you want to delete it for all selected tasks?')
     if delete == YES:
         ask_again = False
     for task in self.task_selector.evaluated_tasks:
         task_dir = os.path.join(self.project_info.project_dir, task)
         results_dir = os.path.join(task_dir, 'results')
         zip_file = os.path.join(task_dir, 'results.zip')
         zf = zipfile.ZipFile(zip_file, 'w', zipfile.ZIP_DEFLATED)
         for dirname, subdirs, files in os.walk(results_dir):
             for filename in files:
                 zf.write(os.path.join(dirname, filename),
                          os.path.join('results', filename))
         zf.close()
         if delete and ask_again:
             if confirm(None, 'Delete directory "results" after compression was selected.\nDo you want to delete it?') == YES:
                 shutil.rmtree(results_dir)
         elif delete:
             shutil.rmtree(results_dir)
     print 'Results compressed'
Esempio n. 20
0
    def _on_exit(self):
        """ Called when the exit action is invoked. """

        parent = self.control

        information(parent, 'Going...')
        warning(parent, 'Going......')
        error(parent, 'Gone!')

        if confirm(parent, 'Should I exit?') == YES:
            self.close()

        return
Esempio n. 21
0
 def promptForSave(self, info, cancel=True):
     """ Prompts the user to save the object, if appropriate. Returns whether
         the user canceled the action that invoked this prompt.
     """
     if self.saveObject.dirty:
         code = confirm(info.ui.control, self.savePromptMessage,
                        title="Save now?", cancel=cancel)
         if code == CANCEL:
             return False
         elif code == YES:
             if not self.save(info):
                 return self.promptForSave(info, cancel)
     return True
Esempio n. 22
0
 def promptForSave(self, info, cancel=True):
     """ Prompts the user to save_to_memory the object, if appropriate. Returns whether
         the user canceled the action that invoked this prompt.
     """
     if self.saveObject.dirty:
         code = confirm(info.ui.control, self.savePromptMessage,
                        title="Save now?", cancel=cancel)
         if code == CANCEL:
             return False
         elif code == YES:
             if not self.save(info):
                 return self.promptForSave(info, cancel)
     return True
Esempio n. 23
0
    def _on_exit(self):
        """ Called when the exit action is invoked. """

        parent = self.control

        print(choose_one(parent, "Make a choice", ["one", "two", "three"]))

        information(parent, "Going...")
        warning(parent, "Going......")
        error(parent, "Gone!")

        if confirm(parent, "Should I exit?") == YES:
            self.close()
Esempio n. 24
0
    def _on_exit(self):
        """ Called when the exit action is invoked. """

        parent = self.control

        print(choose_one(parent, "Make a choice", ['one', 'two', 'three']))

        information(parent, 'Going...')
        warning(parent, 'Going......')
        error(parent, 'Gone!')

        if confirm(parent, 'Should I exit?') == YES:
            self.close()
Esempio n. 25
0
    def _on_exit(self):
        """ Called when the exit action is invoked. """

        parent = self.control

        information(parent, 'Going...')
        warning(parent, 'Going......')
        error(parent, 'Gone!')

        if confirm(parent, 'Should I exit?') == YES:
            self.close()

        return
Esempio n. 26
0
    def _on_exit(self):
        """ Called when the exit action is invoked. """

        parent = self.control

        print((choose_one(parent, "Make a choice", ['one', 'two', 'three'])))

        information(parent, 'Going...')
        warning(parent, 'Going......')
        error(parent, 'Gone!')

        if confirm(parent, 'Should I exit?') == YES:
            self.close()
Esempio n. 27
0
    def _on_import(self):
        """
        Import format: CSV, first column is filename, path relative to CSV.
        others are conditions, type is autodetected.  first row is header
        with names.
        """
        file_dialog = FileDialog()
        file_dialog.wildcard = "CSV files (*.csv)|*.csv|"
        file_dialog.action = 'open'
        file_dialog.open()

        if file_dialog.return_code != PyfaceOK:
            return

        csv = pandas.read_csv(file_dialog.path)
        csv_folder = Path(file_dialog.path).parent

        if self.model.tubes or self.model.tube_traits:
            if confirm(
                    parent=None,
                    message="This will clear the current conditions and tubes! "
                    "Are you sure you want to continue?",
                    title="Clear tubes and conditions?") != YES:
                return

        for col in csv.columns[1:]:
            self.model.tube_traits.append(
                TubeTrait(model=self.model,
                          name=util.sanitize_identifier(col),
                          type='category'))

        for _, row in csv.iterrows():
            filename = csv_folder / row[0]

            try:
                metadata, _ = parse_tube(str(filename), metadata_only=True)
            except Exception as e:
                warning(
                    None,
                    "Had trouble loading file {}: {}".format(filename, str(e)))
                continue

            metadata['CF_File'] = Path(filename).stem
            new_tube = Tube(file=str(filename),
                            parent=self.model,
                            metadata=sanitize_metadata(metadata))
            self.model.tubes.append(new_tube)

            for col in csv.columns[1:]:
                new_tube.trait_set(**{util.sanitize_identifier(col): row[col]})
Esempio n. 28
0
    def delete_selection(self):
        """
        Delete the current selection within the current project.

        """

        # Only do something if we have a current project and a non-empty
        # selection
        current = self.model_service.project
        selection = self.model_service.selection[:]
        if current is not None and len(selection) > 0:
            logger.debug("Deleting selection from Project [%s]", current)

            # Determine the context for the current project.  Raise an error
            # if we can't treat it as a context as then we don't know how
            # to delete anything.
            context = self._get_context_for_object(current)
            if context is None:
                raise Exception("Could not treat Project " +
                                "[%s] as a context" % current)

            # Filter out any objects in the selection that can NOT be deleted.
            deletables = []
            for item in selection:
                rt = self._get_resource_type_for_object(item.obj)
                nt = rt.node_type
                if nt.can_delete(item):
                    deletables.append(item)
                else:
                    logger.debug(
                        "Node type reports selection item [%s] is "
                        "not deletable.",
                        nt,
                    )

            if deletables != []:
                # Confirm the delete operation with the user
                names = "\n\t".join([b.name for b in deletables])
                message = ("You are about to delete the following selected "
                           "items:\n\t%s\n\n"
                           "Are you sure?") % names
                title = "Delete Selected Items?"
                action = confirm(None, message, title)
                if action == YES:

                    # Unbind all the deletable nodes
                    if len(deletables) > 0:
                        self._unbind_nodes(context, deletables)

        return
Esempio n. 29
0
    def load(self, info):
        ''' Load the traits of an experiment from a .params XML file. '''
        from pyface.api import YES, NO, confirm
        if info.object._dirty:
            if confirm(self.info.ui.control, 'Save current parameters before loading?', title='Unsaved parameters') == YES:
                self.save(info)

        params = info.object
        title = 'Load %s parameters' % params._parameters_name
        file_name = self.get_load_file_name_using_PyFace_FileDialog(title)
#        file_name = self.get_load_file_name_using_Traits_FileDialog(title)
        if file_name is not None:
            params.load(file_name)
            from infobiotics.commons.strings import shorten_path
            self.status = "Loaded '%s'." % shorten_path(file_name, 70)
Esempio n. 30
0
    def _on_closing_window(self, window, trait, old, new):
        """ Ask before window closing: save the user DS? Save project?
        """
        from kromatography.ui.menu_entry_names import PREFERENCE_MENU_NAME

        if self.datasource.dirty and len(self.windows_created) == 1:
            title = "Save the User Datasource?"

            msg = ("Some changes have been made to the User Data. Do you want"
                   " to save it and make it the new default User Data?")
            res = confirm(None, msg, title=title)
            if res == YES:
                task = window.active_task
                task.save_user_ds()

        # Ask for all window in case people change their mind
        if self.confirm_on_window_close:
            msg = "Are you sure you want to close the project? All un-saved " \
                  "changes will be lost. <br><br>(You can suppress this" \
                  " confirmation in the Preference panel: <i>Edit > {}</i>.)"
            msg = msg.format(PREFERENCE_MENU_NAME)
            response = confirm(None, msg, title="Close the project?")
            if response == NO:
                new.veto = True
    def _delete_clicked(self, info):
        """Invoked by the "Delete" button."""

        role = self._validate(info)
        if role is None:
            return

        if confirm(None, "Are you sure you want to delete the role \"%s\"?" % role.name) == YES:
            # Delete the data from the database.
            try:
                get_permissions_manager().policy_manager.policy_storage.delete_role(role.name)

                info.ui.dispose()
            except PolicyStorageError as e:
                self._ps_error(e)
Esempio n. 32
0
    def _delete_clicked(self, info):
        """Invoked by the "Delete" button."""

        role = self._validate(info)
        if role is None:
            return

        if confirm(None, "Are you sure you want to delete the role \"%s\"?" % role.name) == YES:
            # Delete the data from the database.
            try:
                get_permissions_manager().policy_manager.policy_storage.delete_role(role.name)

                info.ui.dispose()
            except PolicyStorageError, e:
                self._ps_error(e)
Esempio n. 33
0
    def reset_run(self, ui_info=None):
        '''Save the model into associated pickle file.
        The source DAT file is unaffected.
        '''
        answer = confirm(self._ui_info.ui.control, 'Really reset? Changes will be lost!',
                         title='Reset confirmation',
                         cancel=False,
                         default=YES)

        if answer == YES:
            # ask whether the modified run should be saved
            #
            self.load_run(ui_info)
            self.redraw()
            self.model.unsaved = False
Esempio n. 34
0
 def _validateAndSave(self):
     """ Try to save to the current filepath. Returns whether whether the
         validation was successful/overridden (and the object saved).
     """
     success, message = self.saveObject.validate()
     if success:
         self.saveObject.save()
     else:
         title = "Validation error"
         if (self.allowValidationBypass
                 and confirm(None, message, title=title) == YES):
             self.saveObject.save()
             success = True
         else:
             error(None, message, title=title)
     return success
Esempio n. 35
0
 def _evaluate_fired(self):
     if confirm(None, 'All stored results will be deleted!') == YES:
         cmd_lst = []
         for task in self.task_selector.evaluated_tasks:
             DIR = os.path.join(self.project_info.project_dir, task)
             prepare_dir(os.path.join(DIR, 'results'))
             INP = task + '.inp'
             OUT = task + '.out'
             MSG = task + '.msg'
             ERR = task + '.err'
             cmd_lst.append(ATENA_CMD.format(DIR, INP, OUT, MSG, ERR))
         kwds = {}
         self.__execute(cmd_lst,
                        self.task_selector.evaluated_tasks,
                        self.task_selector.evaluated_tasks_nums,
                        kwds)
Esempio n. 36
0
 def _validateAndSave(self):
     """ Try to save to the current filepath. Returns whether whether the
         validation was successful/overridden (and the object saved).
     """
     success, message = self.saveObject.validate()
     if success:
         self.saveObject.save()
     else:
         title = "Validation error"
         if (self.allowValidationBypass and
                 confirm(None, message, title=title) == YES):
             self.saveObject.save()
             success = True
         else:
             error(None, message, title=title)
     return success
Esempio n. 37
0
    def _generate_fired(self):
        if confirm(None, 'All results will be deleted!') == YES:
            for idx, task in enumerate(self.task_lst):
                task_dir = os.path.join(self.working_dir, task)
                prepare_dir(task_dir)
                outfile = open(os.path.join(task_dir, task + '.inp'), 'w')
#                if self.number_of_fields > 0:
#                    shutil.copy2(os.path.join(self.random_fields_dir, task + '.ccp'), task_dir)
#                    field = task + '.ccp'
                    # outfile.write(m_d.format(field))
                if self.number_of_rvs > 0:
                    self._insert_vars_to_inp(outfile, self.freet_data[idx, :])
                outfile.close()
                print 'TASK ' + task + ' created'
        else:
            pass
Esempio n. 38
0
    def delete_selection(self):
        """
        Delete the current selection within the current project.

        """

        # Only do something if we have a current project and a non-empty
        # selection
        current = self.model_service.project
        selection = self.model_service.selection[:]
        if current is not None and len(selection) > 0:
            logger.debug('Deleting selection from Project [%s]', current)

            # Determine the context for the current project.  Raise an error
            # if we can't treat it as a context as then we don't know how
            # to delete anything.
            context = self._get_context_for_object(current)
            if context is None:
                raise Exception('Could not treat Project ' + \
                    '[%s] as a context' % current)

            # Filter out any objects in the selection that can NOT be deleted.
            deletables = []
            for item in selection:
                rt = self._get_resource_type_for_object(item.obj)
                nt = rt.node_type
                if nt.can_delete(item):
                    deletables.append(item)
                else:
                    logger.debug('Node type reports selection item [%s] is '
                        'not deletable.', nt)

            if deletables != []:
                # Confirm the delete operation with the user
                names = '\n\t'.join([b.name for b in deletables])
                message = ('You are about to delete the following selected '
                    'items:\n\t%s\n\n'
                    'Are you sure?') % names
                title = 'Delete Selected Items?'
                action = confirm(None, message, title)
                if action == YES:

                    # Unbind all the deletable nodes
                    if len(deletables) > 0:
                        self._unbind_nodes(context, deletables)

        return
Esempio n. 39
0
    def _key_changed(self, event):
        """Handles a keyboard event."""
        binding = self.object
        key_name = key_event_to_name(event)
        cur_binding = binding.owner.key_binding_for(binding, key_name)
        if cur_binding is not None:
            result = confirm(
                parent=self.control,
                message=(f"{key_name!r} has already been assigned to "
                         f"'{cur_binding.description}'.\n"
                         "Do you wish to continue?"),
                title="Duplicate Key Definition",
            )
            if result != YES:
                return

        self.value = key_name
Esempio n. 40
0
    def new_study(self, ui_info):

        if ui_info.object.dirty:

            # discard / save dialog

            answer = confirm(ui_info.ui.control, 'Study modified. Save it?',
                             title='New study',
                             cancel=False,
                             default=YES)

            if answer == YES:
                self.save_study(ui_info)

        ui_info.object.file_path = ''
        ui_info.object.new()
        self._set_title_string(ui_info)
Esempio n. 41
0
    def _save_as_fired(self):
        dlg = FileDialog(
            action="save as", wildcard=mrk_out_wildcard, default_filename=self.name, default_directory=self.dir
        )
        dlg.open()
        if dlg.return_code != OK:
            return

        path, ext = os.path.splitext(dlg.path)
        if not path.endswith(out_ext) and len(ext) != 0:
            ValueError("The extension '%s' is not supported." % ext)
        path = path + out_ext

        if os.path.exists(path):
            answer = confirm(None, "The file %r already exists. Should it " "be replaced?", "Overwrite File?")
            if answer != YES:
                return
        self.save(path)
Esempio n. 42
0
    def close(self, info, is_ok):
        if is_ok:
            same = True
            for item in info.object._to_edit:
                for option in item.options.value.keys():
                    if info.object.configuration.get(item.section_name, option) !=\
                            item.options.value[option]:
                        same = False
            if not same:
                save = confirm(None, "Do you want to save changes?", default=YES)
                if save == YES:
                    self._save_configuration_changes(info)
                else:
                    info.object.reset_traits(traits=['_to_edit'])
        else:
            info.object.reset_traits(traits=['_to_edit'])

        return True
Esempio n. 43
0
 def close(self, info, is_ok, from_parent=False):
     return True
     if self.state == 'client':
         return from_parent
     else:
         # The function confirm returns an integer that represents the
         # response that the user requested.  YES is a constant (also
         # imported from the same module as confirm) corresponding to the
         # return value of confirm when the user presses the "yes" button on
         # the dialog.  If any other button (e.g. "no", "abort", etc.) is
         # pressed, the return value will be something other than YES and we
         # will assume that the user has requested not to quit the
         # experiment.
         if confirm(info.ui.control, 'OK to stop?') == YES:
             self.stop(info)
             return True
         else:
             return False
Esempio n. 44
0
    def _save_as_fired(self):
        dlg = FileDialog(action="save as", wildcard=mrk_out_wildcard,
                         default_filename=self.name,
                         default_directory=self.dir)
        dlg.open()
        if dlg.return_code != OK:
            return

        ext = out_ext[dlg.wildcard_index]
        path = dlg.path
        if not path.endswith(ext):
            path = path + ext
            if os.path.exists(path):
                answer = confirm(None, "The file %r already exists. Should it "
                                 "be replaced?", "Overwrite File?")
                if answer != YES:
                    return
        self.save(path)
Esempio n. 45
0
    def delete_user(self):
        """Delete a user."""

        # Get the data from the user.
        vuac = _ViewUserAccount(user_db=self)
        view = _DeleteUserAccountView()
        handler = _UserAccountHandler()

        if vuac.edit_traits(view=view, handler=handler).result:
            # Make absolutely sure.
            name = vuac.name.strip()

            if confirm(None, "Are you sure you want to delete the user \"%s\"?" % name) == YES:
                # Delete the data from the database.
                try:
                    self.user_storage.delete_user(name)
                except UserStorageError, e:
                    self._us_error(e)
Esempio n. 46
0
    def open_file(self, path):
        f = open(path, 'r')
        unpickler = pickle.Unpickler(f)

        try:
            version = unpickler.load()
        except TraitError:
            error(parent=None,
                  message="This doesn't look like a Cytoflow file. Or maybe "
                  "you tried to load a workflow older than version "
                  "0.5?")
            return

        if version != self.model.version:
            ret = confirm(
                parent=None,
                message="This is Cytoflow {}, but you're trying "
                "to load a workflow from version {}. This may or "
                "may not work!  Are you sure you want to proceed?".format(
                    self.model.version, version),
                title="Load workflow?")
            if ret != YES:
                return

        try:
            new_workflow = unpickler.load()
        except TraitError:
            error(parent=None, message="Error trying to load the workflow.")
            return

        # replace the current workflow with the one we just loaded

        if False:  # for debugging the loading of things
            from event_tracer import record_events

            with record_events() as container:
                self.model.workflow = new_workflow

            container.save_to_directory(os.getcwd())
        else:
            self.model.workflow = new_workflow
            self.model.modified = False
            self.model.workflow[0].operation.changed = "api"
Esempio n. 47
0
 def on_new(self):
     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
         
     self.filename = ""
     self.window.title = "Cytoflow"
     
     # clear the workflow
     self.model.workflow = []
     
     # add the import op
     self.handler.add_operation('edu.mit.synbio.cytoflow.operations.import')
     
     self.model.modified = False
Esempio n. 48
0
    def on_new(self):
        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

        # clear the workflow
        self.model.workflow = []

        # add the import op
        self.add_operation(ImportPlugin().id)

        # and select the operation
        self.model.selected = self.model.workflow[0]
Esempio n. 49
0
    def _save_as_fired(self):
        dlg = FileDialog(action="save as", wildcard=mrk_out_wildcard,
                         default_filename=self.name,
                         default_directory=self.dir)
        dlg.open()
        if dlg.return_code != OK:
            return

        path, ext = os.path.splitext(dlg.path)
        if not path.endswith(out_ext) and len(ext) != 0:
            ValueError("The extension '%s' is not supported." % ext)
        path = path + out_ext

        if os.path.exists(path):
            answer = confirm(None, "The file %r already exists. Should it "
                             "be replaced?", "Overwrite File?")
            if answer != YES:
                return
        self.save(path)
Esempio n. 50
0
    def _workbench_exiting(self, event):
        """
        Handle the workbench polling to see if it can exit and shutdown the
        application.

        """

        logger.debug("Detected workbench closing event in [%s]", self)
        # Determine if the current project is dirty, or if an autosaved file
        # exists for this project (i.e., the project has changes which were
        # captured in the autosave operation but were not saved explicitly by
        # the user).  If so, let the user
        # decide whether to veto the closing event, save the project, or
        # ignore the dirty state.
        current = self.model_service.project

        if not (self._get_project_state(current)):
            # Find the active workbench window to be our dialog parent and
            # the application name to use in our dialog title.
            workbench = self.model_service.application.get_service(
                "envisage.ui.workbench.workbench.Workbench")
            window = workbench.active_window
            app_name = workbench.branding.application_name

            # Show a confirmation dialog to the user.
            message = "Do you want to save changes before exiting?"
            title = "%s - %s" % (current.name, app_name)
            action = confirm(window.control,
                             message,
                             title,
                             cancel=True,
                             default=YES)
            if action == YES:
                # If the save is successful, the autosaved file is deleted.
                if not self._save(current, window.control):
                    event.veto = True
            elif action == NO:
                # Delete the autosaved file as the user does not wish to
                # retain the unsaved changes.
                self._clean_autosave_location(current.location.strip())
            elif action == CANCEL:
                event.veto = True
Esempio n. 51
0
    def import_data(self, info, group):
        org_data = info.object.import_data(group)
        if org_data is not None:
            if len(org_data.keys()):
                code = confirm(
                    info.ui.control,
                    'Data imported successfully, continue importing? Press Cancel to discard data',
                    title="Import more data?",
                    cancel=True)

                if code == CANCEL:
                    return
                else:
                    info.object.store_data(org_data)
                    if code == YES:
                        return
                    else:
                        info.ui.dispose()
        else:
            error(None, 'Data extraction unsuccessful', title='No Data')
Esempio n. 52
0
    def _save_as_fired(self):
        dlg = FileDialog(action="save as",
                         wildcard=mrk_out_wildcard,
                         default_filename=self.name,
                         default_directory=self.dir)
        dlg.open()
        if dlg.return_code != OK:
            return

        ext = out_ext[dlg.wildcard_index]
        path = dlg.path
        if not path.endswith(ext):
            path = path + ext
            if os.path.exists(path):
                answer = confirm(
                    None, "The file %r already exists. Should it "
                    "be replaced?", "Overwrite File?")
                if answer != YES:
                    return
        self.save(path)
Esempio n. 53
0
    def _key_changed(self, event):
        """Handles a keyboard event."""
        binding = self.object
        key_name = key_event_to_name(event)
        cur_binding = self.ui.parent.handler.key_binding_for(binding, key_name)
        if cur_binding is not None:
            result = confirm(
                parent=self.control,
                message=(f"{key_name!r} has already been assigned to "
                         f"'{cur_binding.description}'.\n"
                         "Do you wish to continue?"),
                title="Duplicate Key Definition",
            )
            if result != YES:
                return

        self.value = key_name
        # Need to manually update editor because the update to the value
        # won't get transferred to toolkit object due to loopback protection.
        self.update_editor()
Esempio n. 54
0
    def open_study(self, ui_info):

        if ui_info.object.dirty:
            # discard / save dialog

            answer = confirm(ui_info.ui.control, 'Study modified. Save it?',
                             title='Open study',
                             cancel=True,
                             default=YES)

            if answer == YES:
                self.save_study(ui_info)
            elif answer == CANCEL:
                return

        file_name = open_file(filter=['*.pst'],
                              extensions=[FileInfo(), TextInfo()])
        if file_name != '':
            ui_info.object.load(file_name)
            ui_info.object.file_path = file_name
            self._set_title_string(ui_info)
Esempio n. 55
0
    def _save_as_fired(self):
        if self.fid_file:
            default_path = self.fid_file
        else:
            default_path = self.model.default_fid_fname

        dlg = FileDialog(action="save as", wildcard=fid_wildcard,
                         default_path=default_path)
        dlg.open()
        if dlg.return_code != OK:
            return

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

        self.model.save(path)
Esempio n. 56
0
    def _reset_model(self, obj, name, old, new):
        print 'RESET MODEL'
        model = self.model
        if model:
            # check if the model was changed and ask if it is to be saved
            #
            if model.unsaved:

                answer = confirm(self._ui_info.ui.control, 'Run changed, save it?',
                                 title='Save confirmation',
                                 cancel=False,
                                 default=YES)

                if answer == YES:
                    # ask whether the modified run should be saved
                    #
                    self.save_run()
                self.model.unsaved = False

        self.load_run()
        self._reset_plot_template_list()
        self.redraw()