ChangeSignatureDialogViewModel.cs 22.0 KB
Newer Older
J
Jonathon Marolf 已提交
1 2 3
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
4

5 6
#nullable enable

7
using System;
8 9 10
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
S
Sam Harwell 已提交
11
using System.Diagnostics.CodeAnalysis;
12
using System.Linq;
13
using System.Windows;
14 15 16 17 18
using System.Windows.Controls;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.ChangeSignature;
using Microsoft.CodeAnalysis.Editor.Shared.Extensions;
using Microsoft.CodeAnalysis.Editor.Shared.Utilities;
19
using Microsoft.CodeAnalysis.Notification;
20
using Microsoft.CodeAnalysis.Shared.Extensions;
21
using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities;
22
using Microsoft.VisualStudio.Text.Classification;
23 24 25 26
using Roslyn.Utilities;

namespace Microsoft.VisualStudio.LanguageServices.Implementation.ChangeSignature
{
27
    internal partial class ChangeSignatureDialogViewModel : AbstractNotifyPropertyChanged
28
    {
29
        private readonly IClassificationFormatMap _classificationFormatMap;
30
        private readonly ClassificationTypeMap _classificationTypeMap;
31
        private readonly INotificationService _notificationService;
32 33
        private readonly ParameterConfiguration _originalParameterConfiguration;

I
Ivan Basov 已提交
34
        // This can be changed to ParameterViewModel if we will allow adding 'this' parameter.
35
        private readonly ExistingParameterViewModel? _thisParameter;
I
Ivan Basov 已提交
36 37
        private readonly List<ParameterViewModel> _parametersWithoutDefaultValues;
        private readonly List<ParameterViewModel> _parametersWithDefaultValues;
I
Ivan Basov 已提交
38 39

        // This can be changed to ParameterViewModel if we will allow adding 'params' parameter.
40
        private readonly ExistingParameterViewModel? _paramsParameter;
D
David Poeschl 已提交
41 42
        private HashSet<ParameterViewModel> _disabledParameters = new HashSet<ParameterViewModel>();

43 44 45
        private ImmutableArray<SymbolDisplayPart> _declarationParts;
        private bool _previewChanges;

46 47
        private readonly Dictionary<string, List<ParameterViewModel>> _parameterNameOverlapMap = new Dictionary<string, List<ParameterViewModel>>();

48 49 50
        /// <summary>
        /// The document where the symbol we are changing signature is defined.
        /// </summary>
51
        private readonly Document _document;
52
        private readonly int _positionForTypeBinding;
53 54 55 56 57

        internal ChangeSignatureDialogViewModel(
            ParameterConfiguration parameters,
            ISymbol symbol,
            Document document,
58
            int positionForTypeBinding,
59 60
            IClassificationFormatMap classificationFormatMap,
            ClassificationTypeMap classificationTypeMap)
61 62
        {
            _originalParameterConfiguration = parameters;
63
            _document = document;
64
            _positionForTypeBinding = positionForTypeBinding;
65
            _classificationFormatMap = classificationFormatMap;
66 67
            _classificationTypeMap = classificationTypeMap;

68
            _notificationService = document.Project.Solution.Workspace.Services.GetRequiredService<INotificationService>();
69

I
Ivan Basov 已提交
70 71
            // This index is displayed to users. That is why we start it from 1.
            var initialDisplayIndex = 1;
D
David Poeschl 已提交
72

73 74
            if (parameters.ThisParameter != null)
            {
I
Ivan Basov 已提交
75
                _thisParameter = new ExistingParameterViewModel(this, parameters.ThisParameter, initialDisplayIndex++);
D
David Poeschl 已提交
76
                _disabledParameters.Add(_thisParameter);
77 78 79 80
            }

            _declarationParts = symbol.ToDisplayParts(s_symbolDeclarationDisplayFormat);

I
Ivan Basov 已提交
81 82
            _parametersWithoutDefaultValues = CreateParameterViewModels(parameters.ParametersWithoutDefaultValues, ref initialDisplayIndex);
            _parametersWithDefaultValues = CreateParameterViewModels(parameters.RemainingEditableParameters, ref initialDisplayIndex);
D
David Poeschl 已提交
83 84 85

            if (parameters.ParamsParameter != null)
            {
I
Ivan Basov 已提交
86
                _paramsParameter = new ExistingParameterViewModel(this, parameters.ParamsParameter, initialDisplayIndex++);
D
David Poeschl 已提交
87
            }
88

89 90
            UpdateNameConflictMarkers();

91
            var selectedIndex = parameters.SelectedIndex;
I
Ivan Basov 已提交
92 93
            // Currently, we do not support editing the ThisParameter. 
            // Therefore, if there is such parameter, we should move the selectedIndex.
94 95
            if (parameters.ThisParameter != null && selectedIndex == 0)
            {
D
David Poeschl 已提交
96
                // If we have at least one parameter after the ThisParameter, select the first one after This.
I
Ivan Basov 已提交
97
                // Otherwise, do not select anything.
98
                if (parameters.ParametersWithoutDefaultValues.Length + parameters.RemainingEditableParameters.Length > 0)
99 100 101 102 103 104 105 106 107 108 109 110
                {
                    this.SelectedIndex = 1;
                }
                else
                {
                    this.SelectedIndex = null;
                }
            }
            else
            {
                this.SelectedIndex = selectedIndex;
            }
111 112
        }

113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148
        private void UpdateNameConflictMarkers()
        {
            var parameterNameOverlapMap = new Dictionary<string, List<ParameterViewModel>>();
            foreach (var parameter in AllParameters)
            {
                if (!parameter.IsRemoved)
                {
                    parameterNameOverlapMap
                        .GetOrAdd(parameter.ParameterName, _ => new List<ParameterViewModel>())
                        .Add(parameter);
                }
                else
                {
                    parameter.HasParameterNameConflict = Visibility.Collapsed;
                }
            }

            foreach (var parameterName in parameterNameOverlapMap.Keys)
            {
                var matchingParameters = parameterNameOverlapMap[parameterName];
                if (matchingParameters.Count > 1)
                {
                    foreach (var matchingParameter in matchingParameters)
                    {
                        matchingParameter.HasParameterNameConflict = Visibility.Visible;
                    }
                }
                else
                {
                    matchingParameters.Single().HasParameterNameConflict = Visibility.Collapsed;
                }
            }

            NotifyPropertyChanged(nameof(AllParameters));
        }

149
        public AddParameterDialogViewModel CreateAddParameterDialogViewModel()
150
            => new AddParameterDialogViewModel(_document, _positionForTypeBinding);
151

152
        private List<ParameterViewModel> CreateParameterViewModels(ImmutableArray<Parameter> parameters, ref int initialIndex)
I
Ivan Basov 已提交
153 154 155 156 157 158 159 160 161 162 163
        {
            var list = new List<ParameterViewModel>();
            foreach (ExistingParameter existingParameter in parameters)
            {
                list.Add(new ExistingParameterViewModel(this, existingParameter, initialIndex));
                initialIndex++;
            }

            return list;
        }

164 165
        public int GetStartingSelectionIndex()
        {
166 167 168 169 170 171 172 173 174 175 176
            if (_thisParameter == null)
            {
                return 0;
            }

            if (_parametersWithDefaultValues.Count + _parametersWithoutDefaultValues.Count > 0)
            {
                return 1;
            }

            return -1;
177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195
        }

        public bool PreviewChanges
        {
            get
            {
                return _previewChanges;
            }

            set
            {
                _previewChanges = value;
            }
        }

        public bool CanRemove
        {
            get
            {
D
David Poeschl 已提交
196
                if (!EditableParameterSelected(out var index))
197 198 199 200 201 202 203 204 205 206 207 208
                {
                    return false;
                }

                return !AllParameters[index].IsRemoved;
            }
        }

        public bool CanRestore
        {
            get
            {
D
David Poeschl 已提交
209
                if (!EditableParameterSelected(out var index))
210 211 212 213
                {
                    return false;
                }

D
David Poeschl 已提交
214 215 216
                return AllParameters[index].IsRemoved;
            }
        }
217

D
David Poeschl 已提交
218 219 220
        private bool EditableParameterSelected(out int index)
        {
            index = -1;
221

D
David Poeschl 已提交
222 223 224 225
            if (!AllParameters.Any())
            {
                return false;
            }
226

D
David Poeschl 已提交
227 228 229 230 231 232 233 234 235 236
            if (!SelectedIndex.HasValue)
            {
                return false;
            }

            index = SelectedIndex.Value;

            if (index == 0 && _thisParameter != null)
            {
                return false;
237
            }
D
David Poeschl 已提交
238 239

            return true;
240 241 242 243
        }

        internal void Remove()
        {
244
            if (AllParameters[_selectedIndex!.Value] is AddedParameterViewModel)
245
            {
246 247 248 249 250 251 252 253 254 255
                var parameterToRemove = AllParameters[_selectedIndex!.Value];

                if (_parametersWithoutDefaultValues.Contains(parameterToRemove))
                {
                    _parametersWithoutDefaultValues.Remove(parameterToRemove);
                }
                else
                {
                    _parametersWithDefaultValues.Remove(parameterToRemove);
                }
256 257 258
            }
            else
            {
259
                AllParameters[_selectedIndex!.Value].IsRemoved = true;
260 261
            }

262
            UpdateNameConflictMarkers();
263
            RemoveRestoreNotifyPropertyChanged();
264 265 266 267
        }

        internal void Restore()
        {
268
            AllParameters[_selectedIndex!.Value].IsRemoved = false;
269
            UpdateNameConflictMarkers();
270 271 272
            RemoveRestoreNotifyPropertyChanged();
        }

I
Ivan Basov 已提交
273
        internal void AddParameter(AddedParameter addedParameter)
274
        {
D
David Poeschl 已提交
275 276 277 278 279 280 281 282
            if (addedParameter.IsRequired)
            {
                _parametersWithoutDefaultValues.Add(new AddedParameterViewModel(this, addedParameter));
            }
            else
            {
                _parametersWithDefaultValues.Add(new AddedParameterViewModel(this, addedParameter));
            }
283

284
            UpdateNameConflictMarkers();
285 286 287
            RemoveRestoreNotifyPropertyChanged();
        }

288 289
        internal void RemoveRestoreNotifyPropertyChanged()
        {
D
David Poeschl 已提交
290 291 292 293 294 295 296
            NotifyPropertyChanged(nameof(AllParameters));
            NotifyPropertyChanged(nameof(SignatureDisplay));
            NotifyPropertyChanged(nameof(SignaturePreviewAutomationText));
            NotifyPropertyChanged(nameof(CanRemove));
            NotifyPropertyChanged(nameof(RemoveAutomationText));
            NotifyPropertyChanged(nameof(CanRestore));
            NotifyPropertyChanged(nameof(RestoreAutomationText));
297 298 299 300
        }

        internal ParameterConfiguration GetParameterConfiguration()
        {
D
WIP  
David Poeschl 已提交
301 302
            return new ParameterConfiguration(
                _originalParameterConfiguration.ThisParameter,
I
Ivan Basov 已提交
303 304
                _parametersWithoutDefaultValues.Where(p => !p.IsRemoved).Select(p => p.Parameter).ToImmutableArray(),
                _parametersWithDefaultValues.Where(p => !p.IsRemoved).Select(p => p.Parameter).ToImmutableArray(),
D
David Poeschl 已提交
305
                (_paramsParameter == null || _paramsParameter.IsRemoved) ? null : (ExistingParameter)_paramsParameter.Parameter,
D
WIP  
David Poeschl 已提交
306
                selectedIndex: -1);
307 308
        }

C
Cyrus Najmabadi 已提交
309
        private static readonly SymbolDisplayFormat s_symbolDeclarationDisplayFormat = new SymbolDisplayFormat(
310
            genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
311 312 313 314
            miscellaneousOptions:
                SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
                SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
                SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier,
315 316 317 318 319
            extensionMethodStyle: SymbolDisplayExtensionMethodStyle.StaticMethod,
            memberOptions:
                SymbolDisplayMemberOptions.IncludeType |
                SymbolDisplayMemberOptions.IncludeExplicitInterface |
                SymbolDisplayMemberOptions.IncludeAccessibility |
320 321
                SymbolDisplayMemberOptions.IncludeModifiers |
                SymbolDisplayMemberOptions.IncludeRef);
322

C
Cyrus Najmabadi 已提交
323
        private static readonly SymbolDisplayFormat s_parameterDisplayFormat = new SymbolDisplayFormat(
324
            genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters,
325 326 327 328
            miscellaneousOptions:
                SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
                SymbolDisplayMiscellaneousOptions.UseSpecialTypes |
                SymbolDisplayMiscellaneousOptions.IncludeNullableReferenceTypeModifier,
329 330 331 332 333 334 335 336 337 338 339 340
            parameterOptions:
                SymbolDisplayParameterOptions.IncludeType |
                SymbolDisplayParameterOptions.IncludeParamsRefOut |
                SymbolDisplayParameterOptions.IncludeDefaultValue |
                SymbolDisplayParameterOptions.IncludeExtensionThis |
                SymbolDisplayParameterOptions.IncludeName);

        public TextBlock SignatureDisplay
        {
            get
            {
                // TODO: Should probably use original syntax & formatting exactly instead of regenerating here
341
                var displayParts = GetSignatureDisplayParts();
342

343
                var textBlock = displayParts.ToTaggedText().ToTextBlock(_classificationFormatMap, _classificationTypeMap);
344 345 346 347 348 349 350 351 352 353 354

                foreach (var inline in textBlock.Inlines)
                {
                    inline.FontSize = 12;
                }

                textBlock.IsEnabled = false;
                return textBlock;
            }
        }

D
David Poeschl 已提交
355 356 357 358 359 360 361 362
        public string SignaturePreviewAutomationText
        {
            get
            {
                return GetSignatureDisplayParts().Select(sdp => sdp.ToString()).Join(" ");
            }
        }

363
        internal string TEST_GetSignatureDisplayText()
364
            => GetSignatureDisplayParts().Select(p => p.ToString()).Join("");
365 366 367 368 369 370 371 372

        private List<SymbolDisplayPart> GetSignatureDisplayParts()
        {
            var displayParts = new List<SymbolDisplayPart>();

            displayParts.AddRange(_declarationParts);
            displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, "("));

C
Use var  
Cyrus Najmabadi 已提交
373
            var first = true;
374 375 376 377 378 379 380 381 382
            foreach (var parameter in AllParameters.Where(p => !p.IsRemoved))
            {
                if (!first)
                {
                    displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ","));
                    displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Space, null, " "));
                }

                first = false;
383

384
                switch (parameter)
385
                {
386 387 388 389 390
                    case ExistingParameterViewModel existingParameter:
                        displayParts.AddRange(existingParameter.ParameterSymbol.ToDisplayParts(s_parameterDisplayFormat));
                        break;

                    case AddedParameterViewModel addedParameterViewModel:
391
                        var languageService = _document.GetRequiredLanguageService<IChangeSignatureViewModelFactoryService>();
I
Ivan Basov 已提交
392
                        displayParts.AddRange(languageService.GeneratePreviewDisplayParts(addedParameterViewModel));
393 394 395 396
                        break;

                    default:
                        throw ExceptionUtilities.UnexpectedValue(parameter.GetType().ToString());
397
                }
398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413
            }

            displayParts.Add(new SymbolDisplayPart(SymbolDisplayPartKind.Punctuation, null, ")"));
            return displayParts;
        }

        public List<ParameterViewModel> AllParameters
        {
            get
            {
                var list = new List<ParameterViewModel>();
                if (_thisParameter != null)
                {
                    list.Add(_thisParameter);
                }

I
Ivan Basov 已提交
414 415
                list.AddRange(_parametersWithoutDefaultValues);
                list.AddRange(_parametersWithDefaultValues);
416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436

                if (_paramsParameter != null)
                {
                    list.Add(_paramsParameter);
                }

                return list;
            }
        }

        public bool CanMoveUp
        {
            get
            {
                if (!SelectedIndex.HasValue)
                {
                    return false;
                }

                var index = SelectedIndex.Value;
                index = _thisParameter == null ? index : index - 1;
I
Ivan Basov 已提交
437
                if (index <= 0 || index == _parametersWithoutDefaultValues.Count || index >= _parametersWithoutDefaultValues.Count + _parametersWithDefaultValues.Count)
438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456
                {
                    return false;
                }

                return true;
            }
        }

        public bool CanMoveDown
        {
            get
            {
                if (!SelectedIndex.HasValue)
                {
                    return false;
                }

                var index = SelectedIndex.Value;
                index = _thisParameter == null ? index : index - 1;
I
Ivan Basov 已提交
457
                if (index < 0 || index == _parametersWithoutDefaultValues.Count - 1 || index >= _parametersWithoutDefaultValues.Count + _parametersWithDefaultValues.Count - 1)
458 459 460 461 462 463 464 465 466 467 468 469
                {
                    return false;
                }

                return true;
            }
        }

        internal void MoveUp()
        {
            Debug.Assert(CanMoveUp);

470
            var index = SelectedIndex!.Value;
471
            index = _thisParameter == null ? index : index - 1;
I
Ivan Basov 已提交
472
            Move(index < _parametersWithoutDefaultValues.Count ? _parametersWithoutDefaultValues : _parametersWithDefaultValues, index < _parametersWithoutDefaultValues.Count ? index : index - _parametersWithoutDefaultValues.Count, delta: -1);
473 474 475 476 477 478
        }

        internal void MoveDown()
        {
            Debug.Assert(CanMoveDown);

479
            var index = SelectedIndex!.Value;
480
            index = _thisParameter == null ? index : index - 1;
I
Ivan Basov 已提交
481
            Move(index < _parametersWithoutDefaultValues.Count ? _parametersWithoutDefaultValues : _parametersWithDefaultValues, index < _parametersWithoutDefaultValues.Count ? index : index - _parametersWithoutDefaultValues.Count, delta: 1);
482 483 484 485
        }

        private void Move(List<ParameterViewModel> list, int index, int delta)
        {
C
Charles Stoner 已提交
486
            var param = list[index];
487 488 489 490 491
            list.RemoveAt(index);
            list.Insert(index + delta, param);

            SelectedIndex += delta;

D
David Poeschl 已提交
492 493 494
            NotifyPropertyChanged(nameof(AllParameters));
            NotifyPropertyChanged(nameof(SignatureDisplay));
            NotifyPropertyChanged(nameof(SignaturePreviewAutomationText));
495 496
        }

S
Sam Harwell 已提交
497
        internal bool CanSubmit([NotNullWhen(false)] out string? message)
498
        {
499
            var canSubmit = AllParameters.Any(p => p.IsRemoved) ||
500
                AllParameters.Any(p => p is AddedParameterViewModel) ||
D
David Poeschl 已提交
501 502
                    !_parametersWithoutDefaultValues.OfType<ExistingParameterViewModel>().Select(p => p.ParameterSymbol).SequenceEqual(_originalParameterConfiguration.ParametersWithoutDefaultValues.Cast<ExistingParameter>().Select(p => p.Symbol)) ||
                    !_parametersWithDefaultValues.OfType<ExistingParameterViewModel>().Select(p => p.ParameterSymbol).SequenceEqual(_originalParameterConfiguration.RemainingEditableParameters.Cast<ExistingParameter>().Select(p => p.Symbol));
503 504 505

            if (!canSubmit)
            {
S
Sam Harwell 已提交
506 507 508 509 510 511 512 513 514 515 516 517 518
                message = ServicesVSResources.You_must_change_the_signature;
                return false;
            }

            message = null;
            return true;
        }

        internal bool TrySubmit()
        {
            if (!CanSubmit(out var message))
            {
                _notificationService.SendNotification(message, severity: NotificationSeverity.Information);
519 520 521 522
                return false;
            }

            return true;
523 524 525 526
        }

        private bool IsDisabled(ParameterViewModel parameterViewModel)
        {
D
David Poeschl 已提交
527
            return _disabledParameters.Contains(parameterViewModel);
528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547
        }

        private int? _selectedIndex;
        public int? SelectedIndex
        {
            get
            {
                return _selectedIndex;
            }

            set
            {
                var newSelectedIndex = value == -1 ? null : value;
                if (newSelectedIndex == _selectedIndex)
                {
                    return;
                }

                _selectedIndex = newSelectedIndex;

D
David Poeschl 已提交
548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567
                NotifyPropertyChanged(nameof(CanMoveUp));
                NotifyPropertyChanged(nameof(MoveUpAutomationText));
                NotifyPropertyChanged(nameof(CanMoveDown));
                NotifyPropertyChanged(nameof(MoveDownAutomationText));
                NotifyPropertyChanged(nameof(CanRemove));
                NotifyPropertyChanged(nameof(RemoveAutomationText));
                NotifyPropertyChanged(nameof(CanRestore));
                NotifyPropertyChanged(nameof(RestoreAutomationText));
            }
        }

        public string MoveUpAutomationText
        {
            get
            {
                if (!CanMoveUp)
                {
                    return string.Empty;
                }

568
                return string.Format(ServicesVSResources.Move_0_above_1, AllParameters[SelectedIndex!.Value].ShortAutomationText, AllParameters[SelectedIndex!.Value - 1].ShortAutomationText);
D
David Poeschl 已提交
569 570 571 572 573 574 575 576 577 578 579 580
            }
        }

        public string MoveDownAutomationText
        {
            get
            {
                if (!CanMoveDown)
                {
                    return string.Empty;
                }

581
                return string.Format(ServicesVSResources.Move_0_below_1, AllParameters[SelectedIndex!.Value].ShortAutomationText, AllParameters[SelectedIndex!.Value + 1].ShortAutomationText);
D
David Poeschl 已提交
582 583 584 585 586 587 588 589 590 591 592 593
            }
        }

        public string RemoveAutomationText
        {
            get
            {
                if (!CanRemove)
                {
                    return string.Empty;
                }

594
                return string.Format(ServicesVSResources.Remove_0, AllParameters[SelectedIndex!.Value].ShortAutomationText);
D
David Poeschl 已提交
595 596 597 598 599 600 601 602 603 604 605 606
            }
        }

        public string RestoreAutomationText
        {
            get
            {
                if (!CanRestore)
                {
                    return string.Empty;
                }

607
                return string.Format(ServicesVSResources.Restore_0, AllParameters[SelectedIndex!.Value].ShortAutomationText);
608 609
            }
        }
610 611
    }
}