Beispiel #1
0
        public void Cancel()
        {
            if (!Unsaved)
            {
                DialogResult = DialogResult.Cancel;
            }
            else
            {
                DialogResult result = MultiButtonMsgDlg.Show(
                    this,
                    Resources.ConfigureToolsDlg_Cancel_Do_you_wish_to_Save_changes_,
                    MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, true);
                switch (result)
                {
                case DialogResult.Yes:
                    if (SaveTools())
                    {
                        DialogResult = DialogResult.OK;
                    }
                    break;

                case DialogResult.No:
                    DialogResult = DialogResult.Cancel;
                    break;
                }
            }
        }
Beispiel #2
0
        public void OkDialog()
        {
            var chosenLists          = new HashSet <string>(_listsListBoxDriver.Chosen.Select(data => data.ListName));
            var removedListsWithData = DocumentContainer.Document.Settings.DataSettings.Lists
                                       .Where(list => !chosenLists.Contains(list.ListName) && list.RowCount > 0).ToArray();

            if (removedListsWithData.Any())
            {
                string message;
                if (removedListsWithData.Length == 1)
                {
                    var list = removedListsWithData[0];
                    message = string.Format(
                        Resources.DocumentSettingsDlg_OkDialog_The_list___0___has__1__items_in_it__If_you_remove_that_list_from_your_document__those_items_will_be_deleted__Are_you_sure_you_want_to_delete_those_items_from_that_list_,
                        list.ListName, list.RowCount);
                }
                else
                {
                    message = TextUtil.LineSeparate(new[]
                    {
                        Resources.DocumentSettingsDlg_OkDialog_The_following_lists_have_items_in_them_which_will_be_deleted_when_you_remove_the_lists_from_your_document_
                    }
                                                    .Concat(removedListsWithData.Select(list =>
                                                                                        string.Format(Resources.DocumentSettingsDlg_OkDialog_List___0___with__1__items, list.ListName, list.RowCount)))
                                                    .Concat(new[] { Resources.DocumentSettingsDlg_OkDialog_Are_you_sure_you_want_to_delete_those_items_from_those_lists_ }));
                }
                if (MultiButtonMsgDlg.Show(this, message, MultiButtonMsgDlg.BUTTON_OK) == DialogResult.Cancel)
                {
                    return;
                }
            }
            Settings.Default.ListDefList.Clear();
            Settings.Default.ListDefList.AddRange(_listsListBoxDriver.List.Select(list => list.DeleteAllRows()));
            DialogResult = DialogResult.OK;
        }
        /// <summary>
        /// Shows a dialog prompting user to decide whether to use embedded spectra when external spectra are preferred but cannot be found.
        /// Returns 'normal' if the user wants Embedded spectra, 'option1' to retry finding the external spectra, or to 'cancel' to abort the library build.
        /// </summary>
        public static UpdateProgressResponse ShowLibraryMissingExternalSpectraError(Control parentWindow, Exception errorException)
        {
            // E.g. could not find external raw data for MaxQuant msms.txt; ask user if they want to retry with "prefer embedded spectra" option
            if (!BiblioSpecLiteBuilder.IsLibraryMissingExternalSpectraError(errorException, out string spectrumFilename, out string resultsFilepath))
            {
                throw new InvalidOperationException(@"IsLibraryMissingExternalSpectraError returned false");
            }

            // TODO: parse supported file extensions from BiblioSpec or ProteoWizard
            var dialogResult = MultiButtonMsgDlg.Show(parentWindow,
                                                      string.Format(Resources.VendorIssueHelper_ShowLibraryMissingExternalSpectraError_Could_not_find_an_external_spectrum_file_matching__0__in_the_same_directory_as_the_MaxQuant_input_file__1__,
                                                                    spectrumFilename, resultsFilepath) +
                                                      string.Format(Resources.VendorIssueHelper_ShowLibraryMissingExternalSpectraError_ButtonDescriptionsSupportsExtensions__0__, BiblioSpecLiteBuilder.BiblioSpecSupportedFileExtensions),
                                                      Resources.BiblioSpecLiteBuilder_Embedded,
                                                      Resources.AlertDlg_GetDefaultButtonText__Retry, true);

            switch (dialogResult)
            {
            case DialogResult.Cancel: return(UpdateProgressResponse.cancel);

            case DialogResult.Yes: return(UpdateProgressResponse.normal);

            case DialogResult.No: return(UpdateProgressResponse.option1);

            default:
                throw new ArgumentOutOfRangeException();
            }
        }
Beispiel #4
0
 private bool ShowMissingMessage <TItem>(IWin32Window parent, int maxItems, HashSet <TItem> items, Func <TItem, string> printLine, Func <int, MissingMessageLines> getMessageLines)
 {
     if (items.Any())
     {
         var sb           = new StringBuilder();
         var messageLines = getMessageLines(items.Count);
         sb.AppendLine(messageLines.First);
         sb.AppendLine();
         int itemsToShow = Math.Min(items.Count, maxItems);
         var itemsList   = items.ToList();
         for (int i = 0; i < itemsToShow; ++i)
         {
             sb.AppendLine(printLine(itemsList[i]));
         }
         if (itemsToShow < items.Count)
         {
             sb.AppendLine(@"...");
         }
         sb.AppendLine();
         sb.Append(messageLines.Last);
         var dlgFiles = MultiButtonMsgDlg.Show(parent, sb.ToString(), MultiButtonMsgDlg.BUTTON_OK);
         if (dlgFiles == DialogResult.Cancel)
         {
             return(false);
         }
     }
     return(true);
 }
Beispiel #5
0
        private void EnsureChorusAccount()
        {
            if (_chorusAccounts.Any())
            {
                return;
            }
            DialogResult buttonPress = MultiButtonMsgDlg.Show(
                this,
                TextUtil.LineSeparate(
                    Resources.OpenDataSourceDialog_EnsureChorusAccount_No_Chorus_acounts_have_been_specified,
                    Resources.OpenDataSourceDialog_EnsureChorusAccount_Press_Register_to_register_for_an_account_on_the_Chorus_Project,
                    Resources.OpenDataSourceDialog_EnsureChorusAccount_Press_Add_to_use_specify_an_existing_Chorus_account),
                Resources.OpenDataSourceDialog_EnsureChorusAccount_Register, Resources.OpenDataSourceDialog_EnsureChorusAccount_Add, true);

            if (buttonPress == DialogResult.Cancel)
            {
                return;
            }

            if (buttonPress == DialogResult.Yes)
            {
                // person intends to register
                WebHelpers.OpenLink(this, "https://chorusproject.org/pages/register.html"); // Not L10N
            }
            var newAccount = _chorusAccounts.NewItem(this, _chorusAccounts, null);

            if (null != newAccount)
            {
                _chorusAccounts.Add(newAccount);
            }
        }
Beispiel #6
0
        public static bool?OverwriteAnnotations(Control parent, List <AnnotationDef> annotations)
        {
            List <string> annotationTitles = annotations.Select(annotation => annotation.GetKey()).ToList();

            string annotationMultiMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteAnnotations_Annotations_with_the_following_names_already_exist_, String.Empty,
                                                                  @"{0}", String.Empty);

            string annotationSingleMessage =
                TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteAnnotations_An_annotation_with_the_following_name_already_exists_, String.Empty, @"{0}", String.Empty);

            string annotationMessage = annotations.Count == 1 ? annotationSingleMessage : annotationMultiMessage;
            string question          = Resources.ConfigureToolsDlg_OverwriteAnnotations_Do_you_want_to_overwrite_or_keep_the_existing_annotations_;

            string messageFormat = TextUtil.LineSeparate(annotationMessage, question);

            DialogResult result = MultiButtonMsgDlg.Show(
                parent,
                String.Format(messageFormat, TextUtil.LineSeparate(annotationTitles)),
                Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite,
                Resources.ConfigureToolsDlg_OverwriteAnnotations_Keep_Existing, true);

            switch (result)
            {
            case DialogResult.Cancel:
                return(null);

            case DialogResult.Yes:
                return(true);

            case DialogResult.No:
                return(false);
            }
            return(false);
        }
Beispiel #7
0
        private bool SetCalibrationPeptides(ICollection <PeptideDocNode> exclude)
        {
            CheckDisposed();
            var document = Program.ActiveDocumentUI;

            if (!document.Settings.HasResults)
            {
                MessageDlg.Show(this, Resources.CalibrateIrtDlg_UseResults_The_document_must_contain_results_to_calibrate_a_standard);
                return(false);
            }

            var targetResolver = TargetResolver.MakeTargetResolver(document);

            _gridViewDriver.TargetResolver = targetResolver;

            var peptides = document.Molecules.Where(nodePep => nodePep.SchedulingTime.HasValue).ToArray();
            var count    = peptides.Length;

            if (exclude != null && exclude.Count > 0)
            {
                peptides = peptides.Where(nodePep => !exclude.Contains(nodePep)).ToArray();
                count    = peptides.Length;
                if (count < MIN_STANDARD_PEPTIDES)
                {
                    MessageDlg.Show(this,
                                    ModeUIAwareStringFormat(
                                        Resources.CalibrateIrtDlg_SetCalibrationPeptides_The_document_contains_results_for__0__peptide_s__not_in_this_standard__which_is_less_than_the_minimum_requirement_of__1__to_calibrate_a_standard_,
                                        count, MIN_STANDARD_PEPTIDES));
                    return(false);
                }
                else if (count < MIN_SUGGESTED_STANDARD_PEPTIDES)
                {
                    if (MultiButtonMsgDlg.Show(this,
                                               ModeUIAwareStringFormat(
                                                   Resources.CalibrateIrtDlg_SetCalibrationPeptides_The_document_only_contains_results_for__0__peptide_s__not_in_this_standard__It_is_recommended_to_use_at_least__1__peptides_to_calibrate_a_standard__Are_you_sure_you_wish_to_continue_,
                                                   count, MIN_SUGGESTED_STANDARD_PEPTIDES),
                                               MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false) != DialogResult.Yes)
                    {
                        return(false);
                    }
                }
            }
            if (count > 20)
            {
                using (var dlg = new AddIrtStandardsDlg(count, exclude != null && exclude.Count > 0))
                {
                    if (dlg.ShowDialog(this) != DialogResult.OK)
                    {
                        return(false);
                    }

                    count = dlg.StandardCount;
                }
            }

            _gridViewDriver.Recalculate(document, count, exclude);
            return(true);
        }
Beispiel #8
0
        public void OkDialog()
        {
            var reader           = new StringReader(ProteinsText);
            var notFoundLines    = new List <string>();
            var acceptedProteins = new HashSet <string>();
            var setProteinNames  = GetProteinNames();

            string line;

            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }

                if (!setProteinNames.Contains(line))
                {
                    notFoundLines.Add(line);
                }
                else
                {
                    acceptedProteins.Add(line);
                }
            }

            if (acceptedProteins.Count == 0)
            {
                MessageDlg.Show(this, Resources.RefineListDlgProtein_OkDialog_None_of_the_specified_proteins_are_in_the_document_);
                return;
            }
            if (notFoundLines.Count > 0)
            {
                string message;
                if (notFoundLines.Count == 1)
                {
                    message = string.Format(Resources.RefineListDlgProtein_OkDialog_The_protein___0___is_not_in_the_document__Do_you_want_to_continue_, notFoundLines[0]);
                }
                else if (notFoundLines.Count < 15)
                {
                    message = TextUtil.LineSeparate(Resources.RefineListDlgProtein_OkDialog_The_following_proteins_are_not_in_the_document_, string.Empty,
                                                    TextUtil.LineSeparate(notFoundLines), string.Empty,
                                                    Resources.RefineListDlgProtein_OkDialog_Do_you_want_to_continue);
                }
                else
                {
                    message = string.Format(Resources.RefineListDlgProtein_OkDialog_Of_the_specified__0__proteins__1__are_not_in_the_document__Do_you_want_to_continue_,
                                            notFoundLines.Count + acceptedProteins.Count, notFoundLines.Count);
                }
                if (MultiButtonMsgDlg.Show(this, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
                {
                    return;
                }
            }
            AcceptedProteins = acceptedProteins;
            DialogResult     = DialogResult.OK;
        }
Beispiel #9
0
 public void ResetAllSettings()
 {
     if (MultiButtonMsgDlg.Show(this,
                                string.Format(
                                    Resources
                                    .ToolOptionsUI_btnResetSettings_Click_Are_you_sure_you_want_to_clear_all_saved_settings__This_will_immediately_return__0__to_its_original_configuration_and_cannot_be_undone_,
                                    Program.Name), MultiButtonMsgDlg.BUTTON_OK) == DialogResult.OK)
     {
         Settings.Default.Reset();
     }
 }
Beispiel #10
0
        public void RemovePeaks(SrmDocument.DOCUMENT_TYPE docType, BoundDataGridView dataGridView)
        {
            var parent        = FormUtil.FindTopLevelOwner(dataGridView);
            var selectedPeaks = GetSelectedPeaks(dataGridView).Distinct().ToArray();

            if (selectedPeaks.Length == 0)
            {
                MessageDlg.Show(parent, Resources.RemovePeaksAction_RemovePeaks_No_peaks_are_selected);
                return;
            }

            var    lookup  = selectedPeaks.ToLookup(tuple => tuple.Item1, tuple => tuple.Item2).ToArray();
            string message = GetConfirmRemoveMessage(docType, selectedPeaks.Length, lookup.Length);

            if (MultiButtonMsgDlg.Show(parent, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
            {
                return;
            }

            var skylineWindow = GetSkylineWindow(dataGridView);

            lock (skylineWindow.GetDocumentChangeLock())
            {
                skylineWindow.ModifyDocument(Resources.RemovePeaksAction_RemovePeaks_Remove_peaks,
                                             doc =>
                {
                    var longOperationRunner = new LongOperationRunner
                    {
                        ParentControl = parent,
                        JobTitle      = Resources.RemovePeaksAction_RemovePeaks_Removing_Peaks
                    };
                    SrmDocument resultDocument = doc;
                    doc = doc.BeginDeferSettingsChanges();
                    longOperationRunner.Run(broker =>
                    {
                        for (int iGroup = 0; iGroup < lookup.Length; iGroup++)
                        {
                            broker.ProgressValue = iGroup * 100 / lookup.Length;
                            if (broker.IsCanceled)
                            {
                                return;
                            }
                            doc = RemovePeaks(doc, lookup[iGroup]);
                        }

                        resultDocument = doc.EndDeferSettingsChanges(resultDocument, null);
                    });
                    return(resultDocument);
                },
                                             docPair => AuditLogEntry.CreateSingleMessageEntry(
                                                 new MessageInfo(MessageType.removed_peaks, docPair.NewDocumentType, selectedPeaks.Length, lookup.Length)));
            }
        }
Beispiel #11
0
        protected void DeleteSkylineDocNodes(Control owner, ICollection <SkylineDocNode> docNodes)
        {
            if (docNodes.Count == 0)
            {
                return;
            }
            var confirmationMessages = docNodes.Select(node => node.GetDeleteConfirmation(docNodes.Count)).Distinct()
                                       .ToArray();
            string message = confirmationMessages.Length == 1
                ? confirmationMessages[0]
                : SkylineDocNode.GetGenericDeleteConfirmation(docNodes.Count);

            if (MultiButtonMsgDlg.Show(owner, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
            {
                return;
            }
            DeleteDocNodes(new HashSet <IdentityPath>(docNodes.Select(node => node.IdentityPath)));
        }
Beispiel #12
0
        private void TestExportTransitionList()
        {
            var filePathActual = GetTestPath("actual.csv");

            FileEx.SafeDelete(filePathActual);

            var exportDialog = ShowDialog <ExportMethodDlg>(() =>
                                                            SkylineWindow.ShowExportMethodDialog(ExportFileType.List));

            // Export CE optimization transition list
            RunUI(() =>
            {
                exportDialog.InstrumentType            = ExportInstrumentType.THERMO_QUANTIVA;
                exportDialog.ExportStrategy            = ExportStrategy.Single;
                exportDialog.MethodType                = ExportMethodType.Standard;
                exportDialog.OptimizeType              = ExportOptimize.NONE;
                exportDialog.WriteCompensationVoltages = true;
            });
            MultiButtonMsgDlg errDlg1 = null;

            RunDlg <MultiButtonMsgDlg>(() => exportDialog.OkDialog(filePathActual),
                                       // Expect The_settings_for_this_document_do_not_match_the_instrument_type...
                                       errDlg =>
            {
                errDlg1 = errDlg;
                RunUI(errDlg.ClickNo);
            });
            // Expect You_are_missing_compensation_voltages_for_the_following...
            var errDlg2 = FindOpenForms <MultiButtonMsgDlg>().FirstOrDefault(f => f != errDlg1);

            // ReSharper disable once PossibleNullReferenceException
            RunUI(errDlg2.ClickOk);

            WaitForCondition(() => File.Exists(filePathActual));

            var actual   = File.ReadAllLines(filePathActual);
            var expected = File.ReadAllLines(GetTestPath("expected.csv"));

            for (var i = 0; i < Math.Min(expected.Length, actual.Length); i++)
            {
                AssertEx.AreEqual(expected[i], actual[i], $@"transitions differ at line {i}");
            }
            AssertEx.AreEqual(expected.Length, actual.Length, @"different transition count");
        }
Beispiel #13
0
        /// <summary>
        /// Returns true if the tools are saved
        /// </summary>
        private bool PromptForSave()
        {
            if (Unsaved)
            {
                DialogResult toSave = MultiButtonMsgDlg.Show(
                    this,
                    string.Format(Resources.ConfigureToolsDlg_AddFromFile_You_must_save_changes_before_installing_tools__Would_you_like_to_save_changes_),
                    MultiButtonMsgDlg.BUTTON_YES, Resources.ConfigureToolsDlg_AddFromFile_Cancel, false);
                switch (toSave)
                {
                case (DialogResult.Yes):
                    SaveTools();
                    return(true);

                case (DialogResult.No):
                    return(false);
                }
            }
            return(true);
        }
Beispiel #14
0
        public static void DeleteSkylineDocNodes(SkylineWindow skylineWindow, BoundDataGridView dataGridView, IEnumerable <SkylineDocNode> docNodesToDelete)
        {
            var docNodes = (ICollection <SkylineDocNode>)DistinctNodes(docNodesToDelete).ToList();

            if (docNodes.Count == 0)
            {
                return;
            }

            var owner = FormUtil.FindTopLevelOwner(dataGridView);
            var confirmationMessages = docNodes.Select(node => node.GetDeleteConfirmation(docNodes.Count)).Distinct()
                                       .ToArray();
            string message = confirmationMessages.Length == 1
                ? confirmationMessages[0]
                : SkylineDocNode.GetGenericDeleteConfirmation(docNodes.Count);

            if (MultiButtonMsgDlg.Show(owner, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
            {
                return;
            }
            DeleteDocNodes(skylineWindow, new HashSet <IdentityPath>(docNodes.Select(node => node.IdentityPath)));
        }
Beispiel #15
0
        public override void Delete()
        {
            var selectedItems = GetSelectedListItems(BoundDataGridView);

            if (selectedItems.Count == 0)
            {
                return;
            }
            string message = string.Format(Resources.ListViewContext_Delete_Are_you_sure_you_want_to_delete_the__0__selected_items_from_the_list___1___, selectedItems.Count, ListName);

            if (MultiButtonMsgDlg.Show(BoundDataGridView, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
            {
                return;
            }
            SkylineDataSchema.ModifyDocument(EditDescription.Message(ListRef.PROTOTYPE.ChangeName(ListName), string.Format(Resources.ListViewContext_Delete_Delete_from_list___0__, ListName)),
                                             doc =>
            {
                var listData = doc.Settings.DataSettings.FindList(ListName);
                listData     = listData.DeleteItems(selectedItems);
                return(doc.ChangeSettings(
                           doc.Settings.ChangeDataSettings(doc.Settings.DataSettings.ReplaceList(listData))));
            }, AuditLogEntry.SettingsLogFunction);
        }
Beispiel #16
0
        public bool ValidateNewRow(RowItem rowItem, out bool cancelRowEdit)
        {
            cancelRowEdit = false;
            var listItem = rowItem.Value as ListItem;

            if (listItem == null)
            {
                return(true);
            }
            var values = ((ListItem.NewRecordData)listItem.GetRecord()).UncommittedValues;

            if (values.Count == 0)
            {
                return(true);
            }

            try
            {
                ListItemId listItemId;
                var        listData = SkylineDataSchema.Document.Settings.DataSettings.FindList(ListName);
                listData.AddRow(values, out listItemId);
                return(true);
            }
            catch (Exception exception)
            {
                if (MultiButtonMsgDlg.Show(BoundDataGridView,
                                           TextUtil.LineSeparate(Resources.ListViewContext_ValidateNewRow_The_new_row_could_not_be_added_because_of_the_following_error_,
                                                                 exception.Message, Resources.ListViewContext_ValidateNewRow_Press_OK_to_continue_editing_your_row__or_Cancel_to_throw_away_the_new_row_)

                                           , MultiButtonMsgDlg.BUTTON_OK) == DialogResult.Cancel)
                {
                    cancelRowEdit = true;
                }
                return(false);
            }
        }
Beispiel #17
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            string name;

            if (!helper.ValidateNameTextBox(_editing ? (Control)textName : comboMod, out name))
            {
                return;
            }

            // Allow updating the original modification
            if (!_editing || !Equals(name, Modification.Name))
            {
                if (!ModNameAvailable(name))
                {
                    helper.ShowTextBoxError(_editing ? (Control)textName : comboMod,
                                            Resources.EditStaticModDlg_OkDialog_The_modification__0__already_exists, name);
                    return;
                }
            }

            string aas = comboAA.Text;

            if (string.IsNullOrEmpty(aas))
            {
                aas = null;
            }
            else
            {
                // Use the cleanest possible format.
                var sb = new StringBuilder();
                foreach (string aaPart in aas.Split(SEPARATOR_AA))
                {
                    string aa = aaPart.Trim();
                    if (aa.Length == 0)
                    {
                        continue;
                    }
                    if (sb.Length > 0)
                    {
                        sb.Append(", "); // Not L10N
                    }
                    sb.Append(aa);
                }
            }

            string      termString = comboTerm.SelectedItem.ToString();
            ModTerminus?term       = null;

            if (!string.IsNullOrEmpty(termString))
            {
                term = (ModTerminus)Enum.Parse(typeof(ModTerminus), termString);
            }

            if (cbVariableMod.Checked && aas == null && term == null)
            {
                MessageDlg.Show(this, Resources.EditStaticModDlg_OkDialog_Variable_modifications_must_specify_amino_acid_or_terminus);
                comboAA.Focus();
                return;
            }

            string     formula    = null;
            double?    monoMass   = null;
            double?    avgMass    = null;
            LabelAtoms labelAtoms = LabelAtoms.None;

            if (cbChemicalFormula.Checked)
            {
                formula = Formula;
            }
            else
            {
                labelAtoms = LabelAtoms;
            }

            // Get the losses to know whether any exist below
            IList <FragmentLoss> losses = null;

            if (listNeutralLosses.Items.Count > 0)
            {
                losses = Losses.ToArray();
            }

            if (!string.IsNullOrEmpty(formula))
            {
                try
                {
                    SequenceMassCalc.FormulaMass(BioMassCalc.MONOISOTOPIC, formula, SequenceMassCalc.MassPrecision);
                }
                catch (ArgumentException x)
                {
                    _formulaBox.ShowTextBoxErrorFormula(helper, x.Message);
                    return;
                }
            }
            else if (labelAtoms == LabelAtoms.None)
            {
                formula = null;

                // Allow formula and both masses to be empty, if losses are present
                if (NotZero(_formulaBox.MonoMass) || NotZero(_formulaBox.AverageMass) || losses == null)
                {
                    // TODO: Maximum and minimum masses should be formalized and applied everywhere
                    double mass;
                    if (!_formulaBox.ValidateMonoText(helper, -1500, 5000, out mass))
                    {
                        return;
                    }
                    monoMass = mass;
                    if (!_formulaBox.ValidateAverageText(helper, -1500, 5000, out mass))
                    {
                        return;
                    }
                    avgMass = mass;
                }
                // Loss-only modifications may not be variable
                else if (cbVariableMod.Checked)
                {
                    MessageDlg.Show(this, Resources.EditStaticModDlg_OkDialog_The_variable_checkbox_only_applies_to_precursor_modification_Product_ion_losses_are_inherently_variable);
                    cbVariableMod.Focus();
                    return;
                }
            }
            else if (aas == null && term.HasValue)
            {
                MessageDlg.Show(this, Resources.EditStaticModDlg_OkDialog_Labeled_atoms_on_terminal_modification_are_not_valid);
                return;
            }

            RelativeRT relativeRT = RelativeRT.Matching;

            if (comboRelativeRT.Visible && comboRelativeRT.SelectedItem != null)
            {
                relativeRT = RelativeRTExtension.GetEnum(comboRelativeRT.SelectedItem.ToString());
            }

            // Store state of the chemical formula checkbox for next use.
            if (cbChemicalFormula.Visible)
            {
                Settings.Default.ShowHeavyFormula = _formulaBox.FormulaVisible;
            }

            var newMod = new StaticMod(name,
                                       aas,
                                       term,
                                       cbVariableMod.Checked,
                                       formula,
                                       labelAtoms,
                                       relativeRT,
                                       monoMass,
                                       avgMass,
                                       losses);

            foreach (StaticMod mod in _existing)
            {
                if (newMod.Equivalent(mod) && !(_editing && mod.Equals(_originalModification)))
                {
                    if (DialogResult.OK == MultiButtonMsgDlg.Show(
                            this,
                            TextUtil.LineSeparate(Resources.EditStaticModDlg_OkDialog_There_is_an_existing_modification_with_the_same_settings,
                                                  string.Format("'{0}'.", mod.Name), // Not L10N
                                                  string.Empty,
                                                  Resources.EditStaticModDlg_OkDialog_Continue),
                            MultiButtonMsgDlg.BUTTON_OK))
                    {
                        Modification = newMod;
                        DialogResult = DialogResult.OK;
                    }
                    return;
                }
            }

            var uniMod = UniMod.GetModification(name, IsStructural);

            // If the modification name is not found in Unimod, check if there exists a modification in Unimod that matches
            // the dialog modification, and prompt the user to to use the Unimod modification instead.
            if (uniMod == null)
            {
                var matchingMod = UniMod.FindMatchingStaticMod(newMod, IsStructural);
                if (matchingMod != null &&
                    (ModNameAvailable(matchingMod.Name) ||
                     (_editing && Equals(matchingMod.Name, Modification.Name))))
                {
                    var result = MultiButtonMsgDlg.Show(
                        this,
                        TextUtil.LineSeparate(Resources.EditStaticModDlg_OkDialog_There_is_a_Unimod_modification_with_the_same_settings,
                                              string.Empty,
                                              string.Format(Resources.EditStaticModDlg_OkDialog_Click__Unimod__to_use_the_name___0___, matchingMod.Name),
                                              string.Format(Resources.EditStaticModDlg_OkDialog_Click__Custom__to_use_the_name___0___, name)),
                        Resources.EditStaticModDlg_OkDialog_Unimod,
                        Resources.EditStaticModDlg_OkDialog_Custom,
                        true);
                    if (result == DialogResult.Yes)
                    {
                        newMod = matchingMod.MatchVariableAndLossInclusion(newMod);   // Unimod
                    }
                    if (result == DialogResult.Cancel)
                    {
                        return;
                    }
                }
            }
            else
            {
                // If the dialog modification matches the modification of the same name in Unimod,
                // use the UnimodId.
                if (newMod.Equivalent(uniMod))
                {
                    newMod = uniMod.MatchVariableAndLossInclusion(newMod);
                }
                else
                {
                    // Finally, if the modification name is found in Unimod, but the modification in Unimod does not
                    // match the dialog modification, prompt the user to use the Unimod modification definition instead.
                    if (DialogResult.OK != MultiButtonMsgDlg.Show(
                            this,
                            TextUtil.LineSeparate(string.Format(Resources.EditStaticModDlg_OkDialog_This_modification_does_not_match_the_Unimod_specifications_for___0___, name),
                                                  string.Empty,
                                                  Resources.EditStaticModDlg_OkDialog_Use_non_standard_settings_for_this_name),
                            MultiButtonMsgDlg.BUTTON_OK))
                    {
                        return;
                    }
                }
            }

            _modification = newMod;

            DialogResult = DialogResult.OK;
        }
Beispiel #18
0
        private bool AddIrts(LibraryManager.BuildState buildState)
        {
            try
            {
                Library lib;
                ProcessedIrtAverages processed = null;
                var initialMessage             = Resources.LibraryBuildNotificationHandler_LibraryBuildCompleteCallback_Adding_iRTs_to_library;
                using (var longWait = new LongWaitDlg {
                    Text = Resources.LibraryBuildNotificationHandler_LibraryBuildCompleteCallback_Adding_iRTs_to_library
                })
                {
                    var status = longWait.PerformWork(TopMostApplicationForm, 800, monitor =>
                    {
                        var initStatus = new ProgressStatus(initialMessage).ChangeSegments(0, 2);
                        monitor.UpdateProgress(initStatus);
                        lib = NotificationContainer.LibraryManager.TryGetLibrary(buildState.LibrarySpec) ??
                              NotificationContainer.LibraryManager.LoadLibrary(buildState.LibrarySpec, () => new DefaultFileLoadMonitor(monitor));
                        foreach (var stream in lib.ReadStreams)
                        {
                            stream.CloseStream();
                        }
                        if (longWait.IsCanceled)
                        {
                            return;
                        }
                        var irtProviders = lib.RetentionTimeProvidersIrt.ToArray();
                        if (!irtProviders.Any())
                        {
                            irtProviders = lib.RetentionTimeProviders.ToArray();
                        }
                        processed = RCalcIrt.ProcessRetentionTimes(monitor, irtProviders, irtProviders.Length,
                                                                   buildState.IrtStandard.Peptides.ToArray(), new DbIrtPeptide[0]);
                    });
                    if (status.IsCanceled)
                    {
                        return(false);
                    }
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }

                using (var resultsDlg = new AddIrtPeptidesDlg(AddIrtPeptidesLocation.spectral_library, processed))
                {
                    if (resultsDlg.ShowDialog(TopMostApplicationForm) != DialogResult.OK)
                    {
                        return(false);
                    }
                }

                var recalibrate = false;
                if (processed.CanRecalibrateStandards(buildState.IrtStandard.Peptides))
                {
                    using (var dlg = new MultiButtonMsgDlg(
                               TextUtil.LineSeparate(Resources.LibraryGridViewDriver_AddToLibrary_Do_you_want_to_recalibrate_the_iRT_standard_values_relative_to_the_peptides_being_added_,
                                                     Resources.LibraryGridViewDriver_AddToLibrary_This_can_improve_retention_time_alignment_under_stable_chromatographic_conditions_),
                               MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false))
                    {
                        if (dlg.ShowDialog(TopMostApplicationForm) == DialogResult.Yes)
                        {
                            recalibrate = true;
                        }
                    }
                }

                var processedDbIrtPeptides = processed.DbIrtPeptides.ToArray();
                if (!processedDbIrtPeptides.Any())
                {
                    return(false);
                }

                using (var longWait = new LongWaitDlg {
                    Text = Resources.LibraryBuildNotificationHandler_LibraryBuildCompleteCallback_Adding_iRTs_to_library
                })
                {
                    ImmutableList <DbIrtPeptide> newStandards = null;
                    var status = longWait.PerformWork(TopMostApplicationForm, 800, monitor =>
                    {
                        if (recalibrate)
                        {
                            monitor.UpdateProgress(new ProgressStatus().ChangeSegments(0, 2));
                            newStandards = ImmutableList.ValueOf(processed.RecalibrateStandards(buildState.IrtStandard.Peptides));
                            processed    = RCalcIrt.ProcessRetentionTimes(
                                monitor, processed.ProviderData.Select(data => data.Value.RetentionTimeProvider),
                                processed.ProviderData.Count, newStandards.ToArray(), new DbIrtPeptide[0]);
                        }
                        var irtDb = IrtDb.CreateIrtDb(buildState.LibrarySpec.FilePath);
                        irtDb.AddPeptides(monitor, (newStandards ?? buildState.IrtStandard.Peptides).Concat(processedDbIrtPeptides).ToList());
                    });
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
            }
            catch (Exception x)
            {
                MessageDlg.ShowWithException(TopMostApplicationForm,
                                             TextUtil.LineSeparate(Resources.LibraryBuildNotificationHandler_LibraryBuildCompleteCallback_An_error_occurred_trying_to_add_iRTs_to_the_library_, x.Message), x);
                return(false);
            }
            return(true);
        }
Beispiel #19
0
        public void OkDialog()
        {
            IrtType irtType = GetIrtType();

            if (textCalculatorName.Text.Length == 0)
            {
                MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Calculator_name_cannot_be_empty);
                return;
            }
            if (_existing.Select(spec => spec.Name).Contains(textCalculatorName.Text))
            {
                var replaceResult = MultiButtonMsgDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_A_calculator_with_that_name_already_exists___Do_you_want_to_replace_it_,
                                                           MultiButtonMsgDlg.BUTTON_YES,
                                                           MultiButtonMsgDlg.BUTTON_NO,
                                                           false);
                if (replaceResult == DialogResult.No)
                {
                    return;
                }
            }
            if (irtType == IrtType.existing)
            {
                try
                {
                    if (!File.Exists(textOpenDatabase.Text))
                    {
                        MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_contain_a_path_to_a_valid_file_);
                        textOpenDatabase.Focus();
                        return;
                    }
                    var db = IrtDb.GetIrtDb(textOpenDatabase.Text, null);
                    if (db == null)
                    {
                        throw new DatabaseOpeningException(string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Cannot_read_the_database_file__0_, textOpenDatabase.Text));
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(this, string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Failed_to_open_the_database_file___0_, x.Message), x);
                    return;
                }
            }
            else if (irtType == IrtType.separate_list)
            {
                if (textNewDatabase.Text.Length == 0)
                {
                    MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_not_be_empty_);
                    textNewDatabase.Focus();
                    return;
                }
                if (!CreateIrtDatabase(textNewDatabase.Text))
                {
                    return;
                }
            }
            else
            {
                if (textNewDatabaseProteins.Text.Length == 0)
                {
                    MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_iRT_database_field_must_not_be_empty_);
                    textNewDatabaseProteins.Focus();
                    return;
                }
                if (comboBoxProteins.SelectedIndex == -1)
                {
                    MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Please_select_a_protein_containing_the_list_of_standard_peptides_for_the_iRT_calculator_);
                    comboBoxProteins.Focus();
                    return;
                }
                if (!CreateIrtDatabase(textNewDatabaseProteins.Text))
                {
                    return;
                }
            }
            // Make a version of the document with the new calculator in it
            var databaseFileName = irtType == IrtType.existing ? textOpenDatabase.Text :
                                   irtType == IrtType.separate_list ? textNewDatabase.Text :
                                   textNewDatabaseProteins.Text;
            var calculator = new RCalcIrt(textCalculatorName.Text, databaseFileName);
            // CONSIDER: Probably can't use just a static default like 10 below
            var retentionTimeRegression = new RetentionTimeRegression(calculator.Name, calculator, null, null, RetentionTimeRegression.DEFAULT_WINDOW, new List <MeasuredRetentionTime>());
            var docNew = Document.ChangeSettings(Document.Settings.ChangePeptidePrediction(prediction =>
                                                                                           prediction.ChangeRetentionTime(retentionTimeRegression)));

            // Import transition list of standards, if applicable
            if (irtType == IrtType.separate_list)
            {
                try
                {
                    if (!File.Exists(textImportText.Text))
                    {
                        MessageDlg.Show(this, Resources.CreateIrtCalculatorDlg_OkDialog_Transition_list_field_must_contain_a_path_to_a_valid_file_);
                        return;
                    }
                    IdentityPath selectPath;
                    List <MeasuredRetentionTime>     irtPeptides;
                    List <TransitionImportErrorInfo> errorList;
                    var inputs = new MassListInputs(textImportText.Text);
                    docNew = docNew.ImportMassList(inputs, null, out selectPath, out irtPeptides, out _librarySpectra, out errorList);
                    if (errorList.Any())
                    {
                        throw new InvalidDataException(errorList[0].ErrorMessage);
                    }
                    _dbIrtPeptides = irtPeptides.Select(rt => new DbIrtPeptide(rt.PeptideSequence, rt.RetentionTime, true, TimeSource.scan)).ToList();
                    IrtFile        = textImportText.Text;
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(this, string.Format(Resources.CreateIrtCalculatorDlg_OkDialog_Error_reading_iRT_standards_transition_list___0_, x.Message), x);
                    return;
                }
            }
            else if (irtType == IrtType.protein)
            {
                PeptideGroupDocNode selectedGroup = comboBoxProteins.SelectedItem as PeptideGroupDocNode;
// ReSharper disable PossibleNullReferenceException
                _irtPeptideSequences = new HashSet <Target>(selectedGroup.Peptides.Select(pep => pep.ModifiedTarget));
// ReSharper restore PossibleNullReferenceException
            }
            Document     = docNew;
            DialogResult = DialogResult.OK;
        }
Beispiel #20
0
        public void OkDialog()
        {
            var helper = new MessageBoxHelper(this);

            string name;

            if (!helper.ValidateNameTextBox(textName, out name))
            {
                return;
            }

            if (_existing.Contains(en => !ReferenceEquals(_isolationScheme, en) && Equals(name, en.Name)))
            {
                helper.ShowTextBoxError(textName,
                                        Resources.EditIsolationSchemeDlg_OkDialog_The_isolation_scheme_named__0__already_exists, name);
                return;
            }

            if (rbUseResultsData.Checked)
            {
                double?precursorFilter = null;
                bool   filterMargin    = Equals(comboIsolationWidth.SelectedItem, IsolationWidthType.RESULTS_WITH_MARGIN);
                if (!Equals(comboIsolationWidth.SelectedItem, IsolationWidthType.RESULTS))
                {
                    double minFilt = filterMargin ? 0 : TransitionFullScan.MIN_PRECURSOR_MULTI_FILTER;
                    double maxFilt = filterMargin
                        ? TransitionFullScan.MAX_PRECURSOR_MULTI_FILTER_MARGIN
                        : TransitionFullScan.MAX_PRECURSOR_MULTI_FILTER;
                    double precFilt;
                    if (!helper.ValidateDecimalTextBox(textPrecursorFilterMz,
                                                       minFilt, maxFilt, out precFilt))
                    {
                        return;
                    }
                    precursorFilter = precFilt;
                }
                try
                {
                    _isolationScheme = new IsolationScheme(name, SpecialHandling, precursorFilter, null, filterMargin);
                }
                catch (InvalidDataException exception)
                {
                    MessageDlg.ShowException(this, exception);
                    return;
                }
            }
            else
            {
                // Validate prespecified windows.
                List <IsolationWindow> windowList;
                if ((windowList = GetIsolationWindows()) == null)
                {
                    return;
                }


                // Must be at least one window.
                if (windowList.Count == 0)
                {
                    _gridViewDriver.SelectCell(COLUMN_START, 0);
                    MessageDlg.Show(this,
                                    Resources
                                    .EditIsolationSchemeDlg_OkDialog_Specify_Start_and_End_values_for_at_least_one_isolation_window);
                    gridIsolationWindows.Focus();
                    _gridViewDriver.EditCell();
                    return;
                }

                int?windowsPerScan = null;
                if (Equals(SpecialHandling, IsolationScheme.SpecialHandlingType.MULTIPLEXED))
                {
                    int x;
                    if (!helper.ValidateNumberTextBox(textWindowsPerScan,
                                                      IsolationScheme.MIN_MULTIPLEXED_ISOLATION_WINDOWS,
                                                      IsolationScheme.MAX_MULTIPLEXED_ISOLATION_WINDOWS,
                                                      out x))
                    {
                        return;
                    }
                    windowsPerScan = x;
                }
                // Check for overlap and gaps
                var          sortedWindowList = windowList.OrderBy(o => o.Start).ToList();
                bool         gapsOk           = false;
                bool         overlapsOk       = false;
                bool         overlap          = Overlap;
                int          increment        = overlap ? 2 : 1;
                int          subtraction      = overlap ? 3 : 1;
                const double tolerance        = 0.0001;
                for (int i = 0; i < sortedWindowList.Count - subtraction; i += increment)
                {
                    for (int j = 0; j < increment; j++)
                    {
                        IsolationWindow current = sortedWindowList.ElementAt(i + j);
                        IsolationWindow next    = sortedWindowList.ElementAt(i + j + increment);
                        if (!gapsOk && next.Start - current.End > tolerance)
                        {
                            if (MultiButtonMsgDlg.Show(this,
                                                       Resources
                                                       .EditIsolationSchemeDlg_OkDialog_There_are_gaps_in_a_single_cycle_of_your_extraction_windows__Do_you_want_to_continue_,
                                                       MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false) !=
                                DialogResult.Yes)
                            {
                                return;
                            }
                            gapsOk = true;
                        }
                        else if (!overlapsOk && current.End - next.Start > tolerance)
                        {
                            if (MultiButtonMsgDlg.Show(this,
                                                       Resources.EditIsolationSchemeDlgOkDialogThereAreOverlapsContinue,
                                                       MultiButtonMsgDlg.BUTTON_YES,
                                                       MultiButtonMsgDlg.BUTTON_NO, false) != DialogResult.Yes)
                            {
                                return;
                            }
                            overlapsOk = true;
                        }
                    }
                }
                try
                {
                    _isolationScheme = new IsolationScheme(name, windowList, SpecialHandling, windowsPerScan);
                }
                catch (InvalidDataException exception)
                {
                    MessageDlg.ShowException(this, exception);
                    return;
                }
            }

            DialogResult = DialogResult.OK;
        }
Beispiel #21
0
        /// <summary>
        /// UI for warning about unrecognized peptides in imported file
        /// </summary>
        /// <param name="parent"></param>
        /// <returns></returns>
        public bool UnrecognizedPeptidesCancel(IWin32Window parent)
        {
            const int itemsToShow = 10;
            var       peptides    = UnrecognizedPeptides.ToList();

            if (peptides.Any())
            {
                var sb = new StringBuilder();
                sb.AppendLine(peptides.Count == 1
                    ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_peptide_in_the_peak_boundaries_file_was_not_recognized_
                    : string.Format(Resources.SkylineWindow_ImportPeakBoundaries_The_following__0__peptides_in_the_peak_boundaries_file_were_not_recognized__,
                                    peptides.Count));
                sb.AppendLine();
                int peptidesToShow = Math.Min(peptides.Count, itemsToShow);
                for (int i = 0; i < peptidesToShow; ++i)
                {
                    sb.AppendLine(peptides[i]);
                }
                if (peptidesToShow < peptides.Count)
                {
                    sb.AppendLine("..."); // Not L10N
                }
                sb.AppendLine();
                sb.Append(peptides.Count == 1
                    ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_this_peptide_
                    : Resources.SkylineWindow_ImportPeakBoundaries_Continue_peak_boundary_import_ignoring_these_peptides_);
                var dlgPeptides = MultiButtonMsgDlg.Show(parent, sb.ToString(), MultiButtonMsgDlg.BUTTON_OK);
                if (dlgPeptides == DialogResult.Cancel)
                {
                    return(false);
                }
            }
            var files = UnrecognizedFiles.ToList();

            if (files.Any())
            {
                var sb = new StringBuilder();
                sb.AppendLine(files.Count == 1
                    ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_file_name_in_the_peak_boundaries_file_was_not_recognized_
                    : string.Format(Resources.SkylineWindow_ImportPeakBoundaries_The_following__0__file_names_in_the_peak_boundaries_file_were_not_recognized_,
                                    files.Count));
                sb.AppendLine();
                int filesToShow = Math.Min(files.Count, itemsToShow);
                for (int i = 0; i < filesToShow; ++i)
                {
                    sb.AppendLine(files[i]);
                }
                if (filesToShow < files.Count)
                {
                    sb.AppendLine("..."); // Not L10N
                }
                sb.AppendLine();
                sb.Append(files.Count == 1
                    ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_this_file_
                    : Resources.SkylineWindow_ImportPeakBoundaries_Continue_peak_boundary_import_ignoring_these_files_);
                var dlgFiles = MultiButtonMsgDlg.Show(parent, sb.ToString(), MultiButtonMsgDlg.BUTTON_OK);
                if (dlgFiles == DialogResult.Cancel)
                {
                    return(false);
                }
            }
            var charges = UnrecognizedChargeStates.ToList();

            if (charges.Any())
            {
                var sb = new StringBuilder();
                sb.AppendLine(files.Count == 1
                              ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following_peptide__file__and_charge_state_combination_was_not_recognized_
                              : string.Format(Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_The_following__0__peptide__file__and_charge_state_combinations_were_not_recognized_,
                                              charges.Count()));
                sb.AppendLine();
                int chargesToShow = Math.Min(charges.Count, itemsToShow);
                for (int i = 0; i < chargesToShow; ++i)
                {
                    sb.AppendLine(charges[i].PrintLine(' ')); // Not L10N
                }
                if (chargesToShow < charges.Count)
                {
                    sb.AppendLine("..."); // Not L10N
                }
                sb.AppendLine();
                sb.Append(files.Count == 1
                    ? Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_these_charge_states_
                    : Resources.PeakBoundaryImporter_UnrecognizedPeptidesCancel_Continue_peak_boundary_import_ignoring_this_charge_state_);
                var dlgFiles = MultiButtonMsgDlg.Show(parent, sb.ToString(), MultiButtonMsgDlg.BUTTON_OK);
                if (dlgFiles == DialogResult.Cancel)
                {
                    return(false);
                }
            }
            return(true);
        }
Beispiel #22
0
        private bool AddIrtLibraryTable(string path, IrtStandard standard)
        {
            if (!ImportPeptideSearch.HasDocLib || !ImportPeptideSearch.DocLib.IsLoaded)
            {
                return(false);
            }

            var lib = ImportPeptideSearch.DocLib;

            ProcessedIrtAverages processed = null;

            using (var longWait = new LongWaitDlg
            {
                Text = Resources.BuildPeptideSearchLibraryControl_AddIrtLibraryTable_Processing_Retention_Times
            })
            {
                try
                {
                    var status = longWait.PerformWork(WizardForm, 800, monitor =>
                    {
                        var irtProviders = lib.RetentionTimeProvidersIrt.ToArray();
                        if (!irtProviders.Any())
                        {
                            irtProviders = lib.RetentionTimeProviders.ToArray();
                        }
                        processed = RCalcIrt.ProcessRetentionTimes(monitor, irtProviders, irtProviders.Length, standard.Peptides.ToArray(), new DbIrtPeptide[0]);
                    });
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(WizardForm,
                                                 TextUtil.LineSeparate(Resources.BuildPeptideSearchLibraryControl_AddIrtLibraryTable_An_error_occurred_while_processing_retention_times_, x.Message), x);
                    return(false);
                }
            }

            using (var resultsDlg = new AddIrtPeptidesDlg(AddIrtPeptidesLocation.spectral_library, processed))
            {
                if (resultsDlg.ShowDialog(this) != DialogResult.OK)
                {
                    return(false);
                }
            }

            var recalibrate = false;

            if (processed.CanRecalibrateStandards(standard.Peptides))
            {
                using (var dlg = new MultiButtonMsgDlg(
                           TextUtil.LineSeparate(Resources.LibraryGridViewDriver_AddToLibrary_Do_you_want_to_recalibrate_the_iRT_standard_values_relative_to_the_peptides_being_added_,
                                                 Resources.LibraryGridViewDriver_AddToLibrary_This_can_improve_retention_time_alignment_under_stable_chromatographic_conditions_),
                           MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false))
                {
                    if (dlg.ShowDialog(WizardForm) == DialogResult.Yes)
                    {
                        recalibrate = true;
                    }
                }
            }

            using (var longWait = new LongWaitDlg
            {
                Text = Resources.BuildPeptideSearchLibraryControl_AddIrtLibraryTable_Adding_iRTs_to_Library
            })
            {
                try
                {
                    ImmutableList <DbIrtPeptide> newStandards = null;
                    var status = longWait.PerformWork(WizardForm, 800, monitor =>
                    {
                        if (recalibrate)
                        {
                            monitor.UpdateProgress(new ProgressStatus().ChangeSegments(0, 2));
                            newStandards = ImmutableList.ValueOf(processed.RecalibrateStandards(standard.Peptides));
                            processed    = RCalcIrt.ProcessRetentionTimes(
                                monitor, processed.ProviderData.Select(data => data.Value.RetentionTimeProvider),
                                processed.ProviderData.Count, newStandards.ToArray(), new DbIrtPeptide[0]);
                        }
                        var irtDb = IrtDb.CreateIrtDb(path);
                        irtDb.AddPeptides(monitor, (newStandards ?? standard.Peptides).Concat(processed.DbIrtPeptides).ToList());
                    });
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(WizardForm,
                                                 TextUtil.LineSeparate(Resources.BuildPeptideSearchLibraryControl_AddIrtLibraryTable_An_error_occurred_trying_to_add_iRTs_to_the_library_, x.Message), x);
                    return(false);
                }
            }
            return(true);
        }
Beispiel #23
0
        public static bool AddIrts(Library lib, LibrarySpec libSpec, IrtStandard standard, Control parent, bool useTopMostForm = false)
        {
            if (lib == null || !lib.IsLoaded || standard == null || standard.Name.Equals(IrtStandard.EMPTY.Name))
            {
                return(false);
            }

            Control GetParent()
            {
                return(useTopMostForm ? FormUtil.FindTopLevelOpenForm(f => f is BuildLibraryNotification) ?? parent : parent);
            }

            IRetentionTimeProvider[] irtProviders = null;
            var cirtPeptides = new DbIrtPeptide[0];

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Loading_retention_time_providers
            })
            {
                var status = longWait.PerformWork(GetParent(), 800, monitor =>
                {
                    monitor.UpdateProgress(new ProgressStatus().ChangePercentComplete(-1));
                    irtProviders = lib.RetentionTimeProvidersIrt.ToArray();
                    if (!irtProviders.Any())
                    {
                        irtProviders = lib.RetentionTimeProviders.ToArray();
                    }

                    if (ReferenceEquals(standard, IrtStandard.CIRT_SHORT))
                    {
                        var libPeptides = irtProviders.SelectMany(provider => provider.PeptideRetentionTimes).Select(rt => rt.PeptideSequence).ToHashSet();
                        cirtPeptides    = IrtStandard.CIRT.Peptides.Where(pep => libPeptides.Contains(pep.ModifiedTarget)).ToArray();
                    }
                });
                if (status.IsCanceled)
                {
                    return(false);
                }
                if (status.IsError)
                {
                    throw status.ErrorException;
                }
            }

            int?numCirt = null;

            if (cirtPeptides.Length >= RCalcIrt.MIN_PEPTIDES_COUNT)
            {
                using (var dlg = new AddIrtStandardsDlg(cirtPeptides.Length,
                                                        string.Format(
                                                            Resources.LibraryBuildNotificationHandler_AddIrts__0__distinct_CiRT_peptides_were_found__How_many_would_you_like_to_use_as_iRT_standards_,
                                                            cirtPeptides.Length)))
                {
                    if (dlg.ShowDialog(GetParent()) != DialogResult.OK)
                    {
                        return(false);
                    }
                    numCirt = dlg.StandardCount;
                }
            }

            var standardPeptides           = standard.Peptides.ToArray();
            ProcessedIrtAverages processed = null;

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Processing_retention_times
            })
            {
                try
                {
                    var status = longWait.PerformWork(GetParent(), 800, monitor =>
                    {
                        processed = !numCirt.HasValue
                            ? RCalcIrt.ProcessRetentionTimes(monitor, irtProviders, standardPeptides, new DbIrtPeptide[0])
                            : RCalcIrt.ProcessRetentionTimesCirt(monitor, irtProviders, cirtPeptides, numCirt.Value, out standardPeptides);
                    });
                    if (status.IsCanceled)
                    {
                        return(false);
                    }
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(GetParent(),
                                                 TextUtil.LineSeparate(
                                                     Resources.BuildPeptideSearchLibraryControl_AddIrtLibraryTable_An_error_occurred_while_processing_retention_times_,
                                                     x.Message), x);
                    return(false);
                }
            }

            using (var resultsDlg = new AddIrtPeptidesDlg(AddIrtPeptidesLocation.spectral_library, processed))
            {
                if (resultsDlg.ShowDialog(GetParent()) != DialogResult.OK)
                {
                    return(false);
                }
            }

            var recalibrate = false;

            if (processed.CanRecalibrateStandards(standardPeptides))
            {
                using (var dlg = new MultiButtonMsgDlg(
                           TextUtil.LineSeparate(Resources.LibraryGridViewDriver_AddToLibrary_Do_you_want_to_recalibrate_the_iRT_standard_values_relative_to_the_peptides_being_added_,
                                                 Resources.LibraryGridViewDriver_AddToLibrary_This_can_improve_retention_time_alignment_under_stable_chromatographic_conditions_),
                           MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false))
                {
                    recalibrate = dlg.ShowDialog(GetParent()) == DialogResult.Yes;
                }
            }

            var processedDbIrtPeptides = processed.DbIrtPeptides.ToArray();

            if (!processedDbIrtPeptides.Any())
            {
                return(false);
            }

            using (var longWait = new LongWaitDlg {
                Text = Resources.LibraryBuildNotificationHandler_AddIrts_Adding_iRTs_to_library
            })
            {
                try
                {
                    DbIrtPeptide[] newStandards = null;
                    var            status       = longWait.PerformWork(GetParent(), 800, monitor =>
                    {
                        if (recalibrate)
                        {
                            monitor.UpdateProgress(new ProgressStatus().ChangeSegments(0, 2));
                            newStandards = processed.RecalibrateStandards(standardPeptides).ToArray();
                            processed    = RCalcIrt.ProcessRetentionTimes(monitor,
                                                                          processed.ProviderData.Select(data => data.RetentionTimeProvider).ToArray(),
                                                                          newStandards.ToArray(), new DbIrtPeptide[0]);
                        }
                        var irtDb = IrtDb.CreateIrtDb(libSpec.FilePath);
                        irtDb.AddPeptides(monitor, (newStandards ?? standardPeptides).Concat(processed.DbIrtPeptides).ToList());
                    });
                    if (status.IsError)
                    {
                        throw status.ErrorException;
                    }
                }
                catch (Exception x)
                {
                    MessageDlg.ShowWithException(GetParent(),
                                                 TextUtil.LineSeparate(
                                                     Resources.LibraryBuildNotificationHandler_AddIrts_An_error_occurred_trying_to_add_iRTs_to_the_library_,
                                                     x.Message), x);
                    return(false);
                }
            }
            return(true);
        }
        public void OkDialog()
        {
            bool isModel = radioButtonModel.Checked;

            if (isModel)
            {
                var model = _driverPeakScoringModel.SelectedItem;
                if (model == null)
                {
                    MessageDlg.Show(this, Resources.PeakBoundaryCompareTest_DoTest_Must_select_a_model_for_comparison_);
                    return;
                }
                if (!model.IsTrained)
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_Model_must_be_trained_before_it_can_be_used_for_peak_boundary_comparison_);
                    return;
                }
                BoundaryComparer = new ComparePeakBoundaries(model);
            }
            else
            {
                string displayName = textName.Text;
                if (displayName.Length == 0)
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_Comparison_name_cannot_be_empty_);
                    return;
                }
                string filePath = textFilePath.Text;
                if (filePath.Length == 0)
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_File_path_cannot_be_empty_);
                    return;
                }
                if (!File.Exists(filePath))
                {
                    MessageDlg.Show(this, Resources.AddPeakCompareDlg_OkDialog_File_path_field_must_contain_a_path_to_a_valid_file_);
                    return;
                }
                BoundaryComparer = new ComparePeakBoundaries(displayName, filePath);
            }
            var compNames = _existing.Select(comp => comp.Name);

            if (compNames.Contains(BoundaryComparer.Name) && (_current == null || _current.Name != BoundaryComparer.Name))
            {
                var message = isModel
                    ? Resources.AddPeakCompareDlg_OkDialog_The_selected_model_is_already_included_in_the_list_of_comparisons__Please_choose_another_model_
                    : Resources.AddPeakCompareDlg_OkDialog_There_is_already_an_imported_file_with_the_current_name___Please_choose_another_name;
                MessageDlg.Show(this, message);
                return;
            }
            using (var longWaitDlg = new LongWaitDlg
            {
                Text = isModel ? Resources.AddPeakCompareDlg_OkDialog_Comparing_Models : Resources.AddPeakCompareDlg_OkDialog_Comparing_Imported_Files
            })
            {
                try
                {
                    longWaitDlg.PerformWork(this, 1000, pm => BoundaryComparer.GenerateComparison(Document, pm));
                    if (BoundaryComparer.Matches.Count == 0)
                    {
                        throw new IOException(Resources.AddPeakCompareDlg_OkDialog_Document_has_no_eligible_chromatograms_for_analysis___Valid_chromatograms_must_not_be_decoys_or_iRT_standards_);
                    }
                    if (BoundaryComparer.Matches.All(match => match.IsMissingPickedPeak))
                    {
                        throw new IOException(Resources.AddPeakCompareDlg_OkDialog_The_selected_file_or_model_does_not_assign_peak_boundaries_to_any_chromatograms_in_the_document___Please_select_a_different_model_or_file_);
                    }
                    if (BoundaryComparer.HasNoQValues && BoundaryComparer.HasNoScores)
                    {
                        throw new IOException(Resources.AddPeakCompareDlg_OkDialog_The_current_file_or_model_has_no_q_values_or_scores_to_analyze___Either_q_values_or_scores_are_necessary_to_compare_peak_picking_tools_);
                    }
                    if (BoundaryComparer.CountMissing > 0)
                    {
                        var missingMessage = string.Format(Resources.AddPeakCompareDlg_OkDialog_The_imported_file_does_not_contain_any_peak_boundaries_for__0__transition_group___file_pairs___These_chromatograms_will_be_treated_as_if_no_boundary_was_selected_,
                                                           BoundaryComparer.CountMissing);
                        var dlgMissing = MultiButtonMsgDlg.Show(this, missingMessage, MultiButtonMsgDlg.BUTTON_OK);
                        if (dlgMissing == DialogResult.Cancel)
                        {
                            return;
                        }
                    }
                    // Show a warning message and give a chance to cancel, if there are unrecognized peptides
                    if (BoundaryComparer.Importer != null && !BoundaryComparer.Importer.UnrecognizedPeptidesCancel(this))
                    {
                        return;
                    }
                }
                catch (Exception x)
                {
                    string initMessage = isModel
                        ? Resources.AddPeakCompareDlg_OkDialog_Error_comparing_model_peak_boundaries___0_
                        : Resources.AddPeakCompareDlg_OkDialog_Error_applying_imported_peak_boundaries___0_;
                    MessageDlg.ShowWithException(this, string.Format(initMessage, x.Message), x);
                    return;
                }
            }
            DialogResult = DialogResult.OK;
        }
Beispiel #25
0
        public static bool?OverwriteOrInParallel(Control parent,
                                                 string toolCollectionName,
                                                 string toolCollectionVersion,
                                                 List <ReportOrViewSpec> reportList,
                                                 string foundVersion,
                                                 string newCollectionName)
        {
            string message;
            string buttonText;

            if (toolCollectionName != null)
            {
                RelativeVersion relativeVersion = DetermineRelativeVersion(toolCollectionVersion, foundVersion);
                string          toolMessage;
                switch (relativeVersion)
                {
                case RelativeVersion.upgrade:
                    toolMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_currently_installed_, String.Empty,
                                                        String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_upgrade_to__0__or_install_in_parallel_, foundVersion));
                    buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Upgrade;
                    break;

                case RelativeVersion.olderversion:
                    toolMessage =
                        TextUtil.LineSeparate(
                            String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_is_an_older_installation_v_0__of_the_tool__1_, foundVersion, @"{0}"),
                            String.Empty,
                            String.Format(Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_with_the_older_version__0__or_install_in_parallel_,
                                          foundVersion));
                    buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite;
                    break;

                case RelativeVersion.reinstall:
                    toolMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_already_installed_,
                                                        String.Empty,
                                                        Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_reinstall_or_install_in_parallel_);
                    buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Reinstall;
                    break;

                default:
                    toolMessage =
                        TextUtil.LineSeparate(
                            Resources.ConfigureToolsDlg_OverwriteOrInParallel_The_tool__0__is_in_conflict_with_the_new_installation,
                            String.Empty,
                            Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_or_install_in_parallel_);
                    buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite;     // Or update?
                    break;
                }
                message = String.Format(toolMessage, toolCollectionName);
            }
            else //Warn about overwritng report.
            {
                List <string> reportTitles = reportList.Select(sp => sp.GetKey()).ToList();

                string reportMultiMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_following_reports, String.Empty,
                                                                  @"{0}", String.Empty);
                string reportSingleMessage = TextUtil.LineSeparate(Resources.ConfigureToolsDlg_OverwriteOrInParallel_This_installation_would_modify_the_report_titled__0_, String.Empty);

                string reportMessage = reportList.Count == 1 ? reportSingleMessage : reportMultiMessage;
                string question      = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Do_you_wish_to_overwrite_or_install_in_parallel_;
                buttonText = Resources.ConfigureToolsDlg_OverwriteOrInParallel_Overwrite;
                string reportMessageFormat = TextUtil.LineSeparate(reportMessage, question);
                message = String.Format(reportMessageFormat, TextUtil.LineSeparate(reportTitles));
            }

            DialogResult result = MultiButtonMsgDlg.Show(
                parent, message, buttonText, Resources.ConfigureToolsDlg_OverwriteOrInParallel_In_Parallel, true);

            switch (result)
            {
            case DialogResult.Cancel:
                return(null);

            case DialogResult.Yes:
                return(true);

            case DialogResult.No:
                return(false);
            }
            return(false);
        }
Beispiel #26
0
        public void UploadSharedZipFile(Control parent, Server server, string zipFilePath, string folderPath)
        {
            Uri result = null;

            if (server == null)
            {
                return;
            }
            try
            {
                var isCanceled = false;
                using (var waitDlg = new LongWaitDlg {
                    Text = Resources.PublishDocumentDlg_UploadSharedZipFile_Uploading_File
                })
                {
                    waitDlg.PerformWork(parent, 1000, longWaitBroker =>
                    {
                        result = SendZipFile(server, folderPath,
                                             zipFilePath, longWaitBroker);
                        if (longWaitBroker.IsCanceled)
                        {
                            isCanceled = true;
                        }
                    });
                }
                if (!isCanceled) // if user not canceled
                {
                    String message = Resources.WebPanoramaPublishClient_UploadSharedZipFile_Publish_succeeded__would_you_like_to_view_the_file_in_Panorama_;
                    if (MultiButtonMsgDlg.Show(parent, message, MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false)
                        == DialogResult.Yes)
                    {
                        Process.Start(result.ToString());
                    }
                }
            }
            catch (Exception x)
            {
                var panoramaEx = x.InnerException as PanoramaImportErrorException;
                if (panoramaEx != null)
                {
                    var message = Resources.WebPanoramaPublishClient_UploadSharedZipFile_An_error_occured_while_publishing_to_Panorama__would_you_like_to_go_to_Panorama_;
                    if (MultiButtonMsgDlg.Show(parent, message, MultiButtonMsgDlg.BUTTON_YES, MultiButtonMsgDlg.BUTTON_NO, false)
                        == DialogResult.Yes)
                    {
                        Process.Start(panoramaEx.JobUrl.ToString());
                    }
                }
                else
                {
                    MessageDlg.ShowException(parent, x);
                }
            }

            // Change PanoramaUrl setting to the successful url used
            var uriString = server.GetKey() + folderPath;

            uriString = Uri.EscapeUriString(uriString);
            var window = parent as SkylineWindow;

            if (window != null && Uri.IsWellFormedUriString(uriString, UriKind.Absolute)) // cant do Uri.isWellFormed because of port and ip
            {
                window.ChangeDocPanoramaUri(new Uri(uriString));
            }
        }
Beispiel #27
0
        public void OkDialog()
        {
            var reader           = new StringReader(PeptidesText);
            var invalidLines     = new List <string>();
            var notFoundLines    = new List <string>();
            var acceptedPeptides = new List <LibraryKey>();
            var peptideSequences = GetPeptideSequences();

            string line;

            while ((line = reader.ReadLine()) != null)
            {
                line = line.Trim();
                if (string.IsNullOrEmpty(line))
                {
                    continue;
                }
                int foundAt;
                var charge = Transition.GetChargeFromIndicator(line,
                                                               TransitionGroup.MIN_PRECURSOR_CHARGE, TransitionGroup.MAX_PRECURSOR_CHARGE, out foundAt);
                if (!charge.IsEmpty)
                {
                    line = line.Substring(0, foundAt);
                }
                Target target;
                try
                {
                    // CONSIDER(bspratt) small molecule equivalent?
                    if (!FastaSequence.IsExSequence(line))
                    {
                        invalidLines.Add(line);
                        continue;
                    }
                    line   = SequenceMassCalc.NormalizeModifiedSequence(line);
                    target = new Target(line);
                }
                catch (Exception)
                {
                    invalidLines.Add(line);
                    continue;
                }

                if (!peptideSequences.ContainsKey(target))
                {
                    notFoundLines.Add(line);
                }
                else
                {
                    acceptedPeptides.Add(new LibKey(target, charge).LibraryKey);
                }
            }

            if (invalidLines.Count > 0)
            {
                if (invalidLines.Count == 1)
                {
                    MessageDlg.Show(this, string.Format(Resources.RefineListDlg_OkDialog_The_sequence__0__is_not_a_valid_peptide, invalidLines[0]));
                }
                else
                {
                    MessageDlg.Show(this, TextUtil.LineSeparate(Resources.RefineListDlg_OkDialog_The_following_sequences_are_not_valid_peptides, string.Empty, TextUtil.LineSeparate(invalidLines)));
                }
                return;
            }
            if (acceptedPeptides.Count == 0)
            {
                MessageDlg.Show(this, Resources.RefineListDlg_OkDialog_None_of_the_specified_peptides_are_in_the_document);
                return;
            }
            if (notFoundLines.Count > 0)
            {
                string message;
                if (notFoundLines.Count == 1)
                {
                    message = string.Format(Resources.RefineListDlg_OkDialog_The_peptide__0__is_not_in_the_document_Do_you_want_to_continue, notFoundLines[0]);
                }
                else if (notFoundLines.Count < 15)
                {
                    message = TextUtil.LineSeparate(Resources.RefineListDlg_OkDialog_The_following_peptides_are_not_in_the_document, string.Empty,
                                                    TextUtil.LineSeparate(notFoundLines), string.Empty,
                                                    Resources.RefineListDlg_OkDialog_Do_you_want_to_continue);
                }
                else
                {
                    message = string.Format(Resources.RefineListDlg_OkDialog_Of_the_specified__0__peptides__1__are_not_in_the_document_Do_you_want_to_continue,
                                            notFoundLines.Count + acceptedPeptides.Count, notFoundLines.Count);
                }
                if (MultiButtonMsgDlg.Show(this, message, MultiButtonMsgDlg.BUTTON_OK) != DialogResult.OK)
                {
                    return;
                }
            }

            AcceptedPeptides = acceptedPeptides.ToArray();
            DialogResult     = DialogResult.OK;
        }
Beispiel #28
0
        private bool GetPackages()
        {
            ICollection <string> downloadablePackages = new Collection <string>();
            ICollection <string> localPackages        = new Collection <string>();

            AssignPackagesToInstall(ref downloadablePackages, ref localPackages);

            IEnumerable <string> packagePaths = null;

            try
            {
                // download packages
                using (var waitDlg = new LongWaitDlg {
                    ProgressValue = 0
                })
                {
                    waitDlg.PerformWork(this, 500, longWaitBroker => packagePaths = DownloadPackages(longWaitBroker, downloadablePackages));
                }

                // separate packages
                ICollection <string> exePaths    = new Collection <string>();
                ICollection <string> sourcePaths = new Collection <string>();
                foreach (var package in (packagePaths == null) ? localPackages : packagePaths.Concat(localPackages))
                {
                    if (package.EndsWith(@".exe"))
                    {
                        exePaths.Add(package);
                    }
                    else
                    {
                        sourcePaths.Add(package);
                    }
                }

                // first install executable packages, if any
                if (exePaths.Count != 0)
                {
                    using (var waitDlg = new LongWaitDlg(null, false)
                    {
                        Message = Resources.PythonInstaller_GetPackages_Installing_Packages
                    })
                    {
                        waitDlg.PerformWork(this, 500, () => InstallExecutablePackages(exePaths));
                    }
                }

                // then install source paths, if any
                if (sourcePaths.Count != 0)
                {
                    // try and find the path to the pip package manager .exe
                    string pipPath = PythonUtil.GetPipPath(_version);

                    // if it can't be found, install it
                    if (pipPath == null || TestingPip)
                    {
                        DialogResult result = MultiButtonMsgDlg.Show(
                            this,
                            Resources.PythonInstaller_InstallPackages_Skyline_uses_the_Python_tool_setuptools_and_the_Python_package_manager_Pip_to_install_packages_from_source__Click_install_to_begin_the_installation_process_,
                            Resources.PythonInstaller_InstallPackages_Install);
                        if (result == DialogResult.OK && GetPip())
                        {
                            pipPath = PythonUtil.GetPipPath(_version);
                            MessageDlg.Show(this, Resources.PythonInstaller_InstallPackages_Pip_installation_complete_);
                        }
                        else
                        {
                            MessageDlg.Show(this, Resources.PythonInstaller_InstallPackages_Python_package_installation_cannot_continue__Canceling_tool_installation_);
                            return(false);
                        }
                    }

                    using (var waitDlg = new LongWaitDlg(null, false)
                    {
                        Message = Resources.PythonInstaller_GetPackages_Installing_Packages
                    })
                    {
                        waitDlg.PerformWork(this, 500, () => InstallSourcePackages(sourcePaths, pipPath));
                    }
                }
                MessageDlg.Show(this, Resources.PythonInstaller_GetPackages_Package_installation_completed_);
                return(true);
            }
            catch (TargetInvocationException ex)
            {
                if (ex.InnerException is ToolExecutionException)
                {
                    MessageDlg.ShowException(this, ex);
                    return(false);
                }
                throw;
            }
        }
Beispiel #29
0
        private void populateListViewFromDirectory(MsDataFileUri directory)
        {
            _abortPopulateList = false;
            listView.Cursor    = Cursors.Default;
            _waitingForData    = false;
            listView.Items.Clear();

            var listSourceInfo = new List <SourceInfo>();

            if (null == directory || directory is MsDataFilePath && string.IsNullOrEmpty(((MsDataFilePath)directory).FilePath))
            {
                foreach (DriveInfo driveInfo in DriveInfo.GetDrives())
                {
                    string     label      = string.Empty;
                    string     sublabel   = driveInfo.Name;
                    ImageIndex imageIndex = ImageIndex.Folder;
                    _driveReadiness[sublabel] = false;
                    try
                    {
                        switch (driveInfo.DriveType)
                        {
                        case DriveType.Fixed:
                            imageIndex = ImageIndex.LocalDrive;
                            label      = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Local_Drive;
                            if (driveInfo.VolumeLabel.Length > 0)
                            {
                                label = driveInfo.VolumeLabel;
                            }
                            break;

                        case DriveType.CDRom:
                            imageIndex = ImageIndex.OpticalDrive;
                            label      = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Optical_Drive;
                            if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0)
                            {
                                label = driveInfo.VolumeLabel;
                            }
                            break;

                        case DriveType.Removable:
                            imageIndex = ImageIndex.OpticalDrive;
                            label      = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Removable_Drive;
                            if (driveInfo.IsReady && driveInfo.VolumeLabel.Length > 0)
                            {
                                label = driveInfo.VolumeLabel;
                            }
                            break;

                        case DriveType.Network:
                            label = Resources.OpenDataSourceDialog_populateListViewFromDirectory_Network_Share;
                            break;
                        }
                        _driveReadiness[sublabel] = IsDriveReady(driveInfo);
                    }
                    catch (Exception)
                    {
                        label += string.Format(@" ({0})", Resources.OpenDataSourceDialog_populateListViewFromDirectory_access_failure);
                    }

                    string name = driveInfo.Name;
                    if (label != string.Empty)
                    {
                        name = string.Format(@"{0} ({1})", label, name);
                    }

                    listSourceInfo.Add(new SourceInfo(new MsDataFilePath(driveInfo.RootDirectory.FullName))
                    {
                        type         = DataSourceUtil.FOLDER_TYPE,
                        imageIndex   = imageIndex,
                        name         = name,
                        dateModified = GetDriveModifiedTime(driveInfo)
                    });
                }
            }
            else if (directory is RemoteUrl)
            {
                RemoteUrl remoteUrl = directory as RemoteUrl;
                if (string.IsNullOrEmpty(remoteUrl.ServerUrl))
                {
                    foreach (var remoteAccount in _remoteAccounts)
                    {
                        listSourceInfo.Add(new SourceInfo(remoteAccount.GetRootUrl())
                        {
                            name       = remoteAccount.GetKey(),
                            type       = DataSourceUtil.FOLDER_TYPE,
                            imageIndex = ImageIndex.MyNetworkPlaces,
                        });
                    }
                }
                else
                {
                    RemoteAccount remoteAccount = GetRemoteAccount(remoteUrl);
                    if (RemoteSession == null || !Equals(remoteAccount, RemoteSession.Account))
                    {
                        RemoteSession = RemoteSession.CreateSession(remoteAccount);
                    }
                    RemoteServerException exception;
                    bool isComplete = _remoteSession.AsyncFetchContents(remoteUrl, out exception);
                    foreach (var item in _remoteSession.ListContents(remoteUrl))
                    {
                        var imageIndex = DataSourceUtil.IsFolderType(item.Type)
                            ? ImageIndex.Folder
                            : ImageIndex.MassSpecFile;
                        listSourceInfo.Add(new SourceInfo(item.MsDataFileUri)
                        {
                            name         = item.Label,
                            type         = item.Type,
                            imageIndex   = imageIndex,
                            dateModified = item.LastModified,
                            size         = item.FileSize
                        });
                    }
                    if (null != exception)
                    {
                        if (MultiButtonMsgDlg.Show(this, exception.Message, Resources.OpenDataSourceDialog_populateListViewFromDirectory_Retry) != DialogResult.Cancel)
                        {
                            RemoteSession.RetryFetchContents(remoteUrl);
                            isComplete = false;
                        }
                    }
                    if (!isComplete)
                    {
                        listView.Cursor = Cursors.WaitCursor;
                        _waitingForData = true;
                    }
                }
            }
            else if (directory is MsDataFilePath)
            {
                MsDataFilePath msDataFilePath = (MsDataFilePath)directory;
                DirectoryInfo  dirInfo        = new DirectoryInfo(msDataFilePath.FilePath);

                try
                {
                    // subitems: Name, Type, Spectra, Size, Date Modified
                    var arraySubDirInfo = dirInfo.GetDirectories();
                    Array.Sort(arraySubDirInfo, (d1, d2) => string.Compare(d1.Name, d2.Name, StringComparison.CurrentCultureIgnoreCase));
                    var arrayFileInfo = dirInfo.GetFiles();
                    Array.Sort(arrayFileInfo, (f1, f2) => string.Compare(f1.Name, f2.Name, StringComparison.CurrentCultureIgnoreCase));

                    // Calculate information about the files, allowing the user to cancel
                    foreach (var info in arraySubDirInfo)
                    {
                        listSourceInfo.Add(getSourceInfo(info));
                        Application.DoEvents();
                        if (_abortPopulateList)
                        {
                            //MessageBox.Show( "abort" );
                            break;
                        }
                    }

                    if (!_abortPopulateList)
                    {
                        foreach (var info in arrayFileInfo)
                        {
                            listSourceInfo.Add(getSourceInfo(info));
                            Application.DoEvents();
                            if (_abortPopulateList)
                            {
                                //MessageBox.Show( "abort" );
                                break;
                            }
                        }
                    }
                }
                catch (Exception x)
                {
                    var message = TextUtil.LineSeparate(
                        Resources.OpenDataSourceDialog_populateListViewFromDirectory_An_error_occurred_attempting_to_retrieve_the_contents_of_this_directory,
                        x.Message);
                    // Might throw access violation.
                    MessageDlg.ShowWithException(this, message, x);
                    return;
                }
            }

            // Populate the list
            var items = new List <ListViewItem>();

            foreach (var sourceInfo in listSourceInfo)
            {
                if (sourceInfo != null &&
                    (sourceTypeComboBox.SelectedIndex == 0 ||
                     sourceTypeComboBox.SelectedItem.ToString() == sourceInfo.type ||
                     // Always show folders
                     sourceInfo.isFolder))
                {
                    ListViewItem item = new ListViewItem(sourceInfo.ToArray(), (int)sourceInfo.imageIndex)
                    {
                        Tag = sourceInfo,
                    };
                    item.SubItems[2].Tag = sourceInfo.size;
                    item.SubItems[3].Tag = sourceInfo.dateModified;

                    items.Add(item);
                }
            }
            listView.Items.AddRange(items.ToArray());
        }
        public override void Delete()
        {
            if (null == BoundDataGridView)
            {
                return;
            }
            var selectedRows = GetSelectedRows <FoldChangeBindingSource.FoldChangeRow>(BoundDataGridView);

            if (!selectedRows.Any())
            {
                MessageDlg.Show(BoundDataGridView, GroupComparisonStrings.GroupComparisonViewContext_Delete_No_rows_are_selected);
                return;
            }
            var docNodes = new Dictionary <IdentityPath, SkylineDocNode>();

            foreach (var row in selectedRows)
            {
                if (row.Peptide != null)
                {
                    docNodes[row.Peptide.IdentityPath] = row.Peptide;
                }
                else
                {
                    docNodes[row.Protein.IdentityPath] = row.Protein;
                }
            }
            string message;

            if (docNodes.Count == 1)
            {
                var peptide = docNodes.Values.First() as Peptide;
                if (null != peptide)
                {
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_the_peptide__0_, peptide);
                }
                else
                {
                    var protein = docNodes.Values.First() as Protein;
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_the_protein__0_, protein);
                }
            }
            else
            {
                if (docNodes.Values.First() is Peptide)
                {
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_these__0__peptides, docNodes.Count);
                }
                else
                {
                    message = string.Format(GroupComparisonStrings.GroupComparisonViewContext_Delete_Are_you_sure_you_want_to_delete_these__0__proteins, docNodes.Count);
                }
            }
            if (MultiButtonMsgDlg.Show(BoundDataGridView, message, Resources.OK) != DialogResult.OK)
            {
                return;
            }
            var identityPathsToDelete = new HashSet <IdentityPath>(docNodes.Keys);
            var skylineWindow         = ((SkylineDataSchema)DataSchema).SkylineWindow;

            if (null != skylineWindow)
            {
                skylineWindow.ModifyDocument(GroupComparisonStrings.GroupComparisonViewContext_Delete_Delete_items, doc => DeleteProteins(doc, identityPathsToDelete));
            }
        }