Browse Source

Merge pull request #1 from icsharpcode/master

update
pull/504/head
julodnik 11 years ago
parent
commit
dbf74662a0
  1. 16
      SharpDevelop.Tests.sln
  2. 8
      SharpDevelop.sln
  3. 121
      src/AddIns/Analysis/CodeCoverage/Project/Src/CodeCoverageMethodElement.cs
  4. 20
      src/AddIns/BackendBindings/CSharpBinding/Project/CSharpBinding.addin
  5. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/CSharpBinding.csproj
  6. 259
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/CSharpLanguageBinding.cs
  7. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpCompletionBinding.cs
  8. 1
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpCompletionContext.cs
  9. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpInsightItem.cs
  10. 4
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpMethodInsight.cs
  11. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/OverrideCompletionData.cs
  12. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/OverrideEqualsGetHashCodeCompletionData.cs
  13. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/OverrideToStringCompletionData.cs
  14. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/PartialCompletionData.cs
  15. 4
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormatter.cs
  16. 150
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormattingOptionsContainer.cs
  17. 128
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormattingPolicies.cs
  18. 74
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormattingStrategy.cs
  19. 53
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/FormattingOptionBinding.cs
  20. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormsDesigner/CSharpDesignerGenerator.cs
  21. 3
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormsDesigner/SecondaryDisplayBinding.cs
  22. 36
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/OptionPanels/CSharpFormattingEditor.xaml
  23. 42
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/OptionPanels/CSharpFormattingEditor.xaml.cs
  24. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/OptionPanels/CSharpFormattingOptionPanel.xaml
  25. 15
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/OptionPanels/CSharpFormattingOptionPanel.xaml.cs
  26. 15
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/OptionPanels/CSharpProjectFormattingOptions.xaml.cs
  27. 150
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Parser/CSharpSymbolSearch.cs
  28. 7
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Refactoring/CSharpCodeGenerator.cs
  29. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Refactoring/InsertCtorDialog.xaml.cs
  30. 2
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Refactoring/MoveTypeToFileContextAction.cs
  31. 9
      src/AddIns/BackendBindings/CSharpBinding/Project/Src/Refactoring/SDRefactoringContext.cs
  32. 6
      src/AddIns/Debugger/Debugger.AddIn/Service/DebuggeeExceptionForm.cs
  33. 3
      src/AddIns/Debugger/Debugger.Core/NDebugger.cs
  34. 12
      src/AddIns/Debugger/Debugger.Core/Process.cs
  35. 18
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/CodeEditorAdapter.cs
  36. 1
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/ContextActions/GoToEntityAction.cs
  37. 1
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/QuickClassBrowser.cs
  38. 11
      src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/XmlDoc/XmlDocTooltipProvider.cs
  39. 19
      src/AddIns/DisplayBindings/FormsDesigner/Project/Src/FormKeyHandler.cs
  40. 8
      src/AddIns/DisplayBindings/HexEditor/Project/Src/Editor.cs
  41. 28
      src/AddIns/DisplayBindings/ILSpyAddIn/ILSpyParser.cs
  42. 1
      src/AddIns/DisplayBindings/IconEditor/PickFormatDialog.Designer.cs
  43. 52
      src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Project/DesignPanel.cs
  44. 48
      src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Project/Extensions/CanvasPlacementSupport.cs
  45. 12
      src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Project/Extensions/SnaplinePlacementBehavior.cs
  46. 12
      src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Project/Xaml/XamlModelProperty.cs
  47. 115
      src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Tests/Designer/ModelTests.cs
  48. 69
      src/AddIns/DisplayBindings/WpfDesign/WpfDesign.XamlDom/Project/MarkupExtensionPrinter.cs
  49. 9
      src/AddIns/DisplayBindings/WpfDesign/WpfDesign.XamlDom/Project/XamlDocument.cs
  50. 6
      src/AddIns/DisplayBindings/WpfDesign/WpfDesign/Project/DesignItemProperty.cs
  51. 12
      src/AddIns/Misc/FiletypeRegisterer/Project/Src/RegisterFiletypesPanel.Designer.cs
  52. 7
      src/AddIns/Misc/FiletypeRegisterer/Project/Src/RegisterFiletypesPanel.cs
  53. 4
      src/AddIns/Misc/PackageManagement/Cmdlets/Project/Src/InstallPackageCmdlet.cs
  54. 7
      src/AddIns/Misc/PackageManagement/Cmdlets/Project/Src/PackageManagementCmdlet.cs
  55. 4
      src/AddIns/Misc/PackageManagement/Cmdlets/Project/Src/UninstallPackageCmdlet.cs
  56. 4
      src/AddIns/Misc/PackageManagement/Cmdlets/Project/Src/UpdatePackageCmdlet.cs
  57. 14
      src/AddIns/Misc/PackageManagement/Cmdlets/Test/Src/InstallPackageCmdletTests.cs
  58. 16
      src/AddIns/Misc/PackageManagement/Cmdlets/Test/Src/UninstallPackageCmdletTests.cs
  59. 14
      src/AddIns/Misc/PackageManagement/Cmdlets/Test/Src/UpdatePackageCmdletTests.cs
  60. 3
      src/AddIns/Misc/PackageManagement/Project/PackageManagement.csproj
  61. 17
      src/AddIns/Misc/PackageManagement/Project/Src/Design/FakeSettings.cs
  62. 5
      src/AddIns/Misc/PackageManagement/Project/Src/PackageManagementOptions.cs
  63. 4
      src/AddIns/Misc/PackageManagement/Project/Src/RegisteredPackageSourceSettings.cs
  64. 31
      src/AddIns/Misc/PackageManagement/Project/Src/RestorePackagesCommand.cs
  65. 16
      src/AddIns/Misc/PackageManagement/Project/Src/Scripting/ICmdletLogger.cs
  66. 1
      src/AddIns/Misc/PackageManagement/Project/Src/Scripting/IPackageManagementConsoleHost.cs
  67. 5
      src/AddIns/Misc/PackageManagement/Project/Src/Scripting/PackageManagementConsoleHost.cs
  68. 75
      src/AddIns/Misc/PackageManagement/Project/Src/Scripting/PackageManagementConsoleHostLogger.cs
  69. 5
      src/AddIns/Misc/PackageManagement/Project/Src/Scripting/PowerShellMissingConsoleHost.cs
  70. 2
      src/AddIns/Misc/PackageManagement/Project/Src/SharpDevelopPackageManagerFactory.cs
  71. 15
      src/AddIns/Misc/PackageManagement/Project/Src/SolutionPackageRepositoryPath.cs
  72. 2
      src/AddIns/Misc/PackageManagement/Test/PackageManagement.Tests.csproj
  73. 38
      src/AddIns/Misc/PackageManagement/Test/Src/Helpers/FakeCmdletLogger.cs
  74. 16
      src/AddIns/Misc/PackageManagement/Test/Src/Helpers/FakePackageManagementConsoleHost.cs
  75. 85
      src/AddIns/Misc/PackageManagement/Test/Src/Scripting/PackageManagementConsoleHostLoggerTests.cs
  76. 24
      src/AddIns/Misc/PackageManagement/Test/Src/SolutionPackageRepositoryPathTests.cs
  77. 16
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/DesignableItems/BaseLineItem.cs
  78. 20
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/DesignableItems/BaseRectangleItem.cs
  79. 34
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/DesignableItems/BaseTextItem.cs
  80. 4
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/DesignerBinding/DesignerBinding.cs
  81. 5
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/DesignerBinding/InternalReportLoader.cs
  82. 7
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/Factory/CreateFormSheetFromModel.cs
  83. 16
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/Services/HelpService.cs
  84. 2
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/Services/ToolboxService.cs
  85. 6
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/TypeProvider/AbstractItemTypeProvider.cs
  86. 6
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/TypeProvider/TypeProviderHelper.cs
  87. 6
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/XML/ReportDefinitionParser.cs
  88. 8
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/ICSharpCode.Reporting.csproj
  89. 5
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/Arrange/ArrangeStrategy.cs
  90. 71
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/BaseClasses/TextDrawer.cs
  91. 12
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/Collections.cs
  92. 3
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataManager/DataCollection.cs
  93. 22
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataManager/Listhandling/CollectionDataSource.cs
  94. 102
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/Comparer/BaseComparer.cs
  95. 115
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/Comparer/SortComparer.cs
  96. 3
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/ExtendedPropertyDescriptor.cs
  97. 8
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/ExtendedTypeDescriptor.cs
  98. 2
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/PropertyMemberAccessore.cs
  99. 4
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/Exporter/Visitors/AbstractVisitor.cs
  100. 2
      src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/Exporter/Visitors/DebugVisitor.cs
  101. Some files were not shown because too many files have changed in this diff Show More

16
SharpDevelop.Tests.sln

@ -290,10 +290,10 @@ Global @@ -290,10 +290,10 @@ Global
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.Debug|Any CPU.Build.0 = net_4_0_Debug|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.Release|Any CPU.ActiveCfg = net_4_0_Release|Any CPU
{D68133BD-1E63-496E-9EDE-4FBDBF77B486}.Release|Any CPU.Build.0 = net_4_0_Release|Any CPU
{6222A3A1-83CE-47A3-A4E4-A018F82D44D8}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6222A3A1-83CE-47A3-A4E4-A018F82D44D8}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6222A3A1-83CE-47A3-A4E4-A018F82D44D8}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6222A3A1-83CE-47A3-A4E4-A018F82D44D8}.Release|Any CPU.Build.0 = Release|Any CPU
{6222A3A1-83CE-47A3-A4E4-A018F82D44D8}.Debug|Any CPU.ActiveCfg = Debug|WithNRefactory
{6222A3A1-83CE-47A3-A4E4-A018F82D44D8}.Debug|Any CPU.Build.0 = Debug|WithNRefactory
{6222A3A1-83CE-47A3-A4E4-A018F82D44D8}.Release|Any CPU.ActiveCfg = Release|WithNRefactory
{6222A3A1-83CE-47A3-A4E4-A018F82D44D8}.Release|Any CPU.Build.0 = Release|WithNRefactory
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|Any CPU.ActiveCfg = net_4_5_Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Debug|Any CPU.Build.0 = net_4_5_Debug|Any CPU
{3B2A5653-EC97-4001-BB9B-D90F1AF2C371}.Release|Any CPU.ActiveCfg = net_4_5_Release|Any CPU
@ -322,10 +322,10 @@ Global @@ -322,10 +322,10 @@ Global
{2FF700C2-A38A-48BD-A637-8CAFD4FE6237}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2FF700C2-A38A-48BD-A637-8CAFD4FE6237}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2FF700C2-A38A-48BD-A637-8CAFD4FE6237}.Release|Any CPU.Build.0 = Release|Any CPU
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Release|Any CPU.Build.0 = Release|Any CPU
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Debug|Any CPU.ActiveCfg = Debug|WithNRefactory
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Debug|Any CPU.Build.0 = Debug|WithNRefactory
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Release|Any CPU.ActiveCfg = Release|WithNRefactory
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Release|Any CPU.Build.0 = Release|WithNRefactory
{4139CCF6-FB49-4A9D-B2CF-331E9EA3198D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4139CCF6-FB49-4A9D-B2CF-331E9EA3198D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4139CCF6-FB49-4A9D-B2CF-331E9EA3198D}.Release|Any CPU.ActiveCfg = Release|Any CPU

8
SharpDevelop.sln

@ -263,10 +263,10 @@ Global @@ -263,10 +263,10 @@ Global
{2FF700C2-A38A-48BD-A637-8CAFD4FE6237}.Debug|Any CPU.Build.0 = Debug|Any CPU
{2FF700C2-A38A-48BD-A637-8CAFD4FE6237}.Release|Any CPU.ActiveCfg = Release|Any CPU
{2FF700C2-A38A-48BD-A637-8CAFD4FE6237}.Release|Any CPU.Build.0 = Release|Any CPU
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Debug|Any CPU.Build.0 = Debug|Any CPU
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Release|Any CPU.ActiveCfg = Release|Any CPU
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Release|Any CPU.Build.0 = Release|Any CPU
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Debug|Any CPU.ActiveCfg = Debug|WithNRefactory
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Debug|Any CPU.Build.0 = Debug|WithNRefactory
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Release|Any CPU.ActiveCfg = Release|WithNRefactory
{6C55B776-26D4-4DB3-A6AB-87E783B2F3D1}.Release|Any CPU.Build.0 = Release|WithNRefactory
{4139CCF6-FB49-4A9D-B2CF-331E9EA3198D}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{4139CCF6-FB49-4A9D-B2CF-331E9EA3198D}.Debug|Any CPU.Build.0 = Debug|Any CPU
{4139CCF6-FB49-4A9D-B2CF-331E9EA3198D}.Release|Any CPU.ActiveCfg = Release|Any CPU

121
src/AddIns/Analysis/CodeCoverage/Project/Src/CodeCoverageMethodElement.cs

@ -58,6 +58,7 @@ namespace ICSharpCode.CodeCoverage @@ -58,6 +58,7 @@ namespace ICSharpCode.CodeCoverage
public string FileID { get; private set; }
public string FileName { get; private set; }
public string FileNameExt { get; private set; }
public bool IsVisited { get; private set; }
public int CyclomaticComplexity { get; private set; }
public decimal SequenceCoverage { get; private set; }
@ -86,9 +87,14 @@ namespace ICSharpCode.CodeCoverage @@ -86,9 +87,14 @@ namespace ICSharpCode.CodeCoverage
this.FileID = GetFileRef();
this.FileName = String.Empty;
this.FileNameExt = String.Empty;
if (!String.IsNullOrEmpty(this.FileID)) {
if (results != null) {
this.FileName = results.GetFileName(this.FileID);
try {
this.FileNameExt = Path.GetExtension(this.FileName).ToLowerInvariant();
}
catch {}
if (cacheFileName != this.FileName) {
cacheFileName = this.FileName;
cacheDocument = GetSource (cacheFileName);
@ -220,14 +226,19 @@ namespace ICSharpCode.CodeCoverage @@ -220,14 +226,19 @@ namespace ICSharpCode.CodeCoverage
// -> this method SP with lowest Line/Column
void getBodyStartSP() {
if (this.SequencePoints.Count != 0) {
foreach (CodeCoverageSequencePoint sp in this.SequencePoints) {
if (sp.FileID != this.FileID) continue;
if (this.BodyStartSP == null || (sp.Line < this.BodyStartSP.Line) ||
(sp.Line == this.BodyStartSP.Line && sp.Column < this.BodyStartSP.Column)
) {
this.BodyStartSP = sp;
if (this.FileNameExt == ".cs") {
foreach (CodeCoverageSequencePoint sp in this.SequencePoints) {
if (sp.FileID != this.FileID) continue;
if (this.BodyStartSP == null || (sp.Line < this.BodyStartSP.Line) ||
(sp.Line == this.BodyStartSP.Line && sp.Column < this.BodyStartSP.Column)
) {
this.BodyStartSP = sp;
}
}
}
else {
this.BodyStartSP = this.SequencePoints.First();
}
}
}
@ -236,29 +247,34 @@ namespace ICSharpCode.CodeCoverage @@ -236,29 +247,34 @@ namespace ICSharpCode.CodeCoverage
// and lowest Offset (when duplicated bw ccrewrite)
void getBodyFinalSP() {
if (this.SequencePoints.Count != 0) {
for (int i = this.SequencePoints.Count-1; i > 0; i--) {
var sp = this.SequencePoints[i];
if (sp.FileID != this.FileID) continue;
if (sp.Content != "}") continue;
if (this.BodyFinalSP == null || (sp.Line > this.BodyFinalSP.Line) ||
(sp.Line == this.BodyFinalSP.Line && sp.Column >= this.BodyFinalSP.Column)
) {
// ccrewrite ContractClass/ContractClassFor
// adds duplicate method end-sequence-point "}"
//
// Take duplicate BodyFinalSP with lower Offset
// Because IL.Offset of second duplicate
// will extend branch coverage of this method
// by coverage of ContractClassFor inserted SequencePoint!
if (this.BodyFinalSP != null &&
sp.Line == this.BodyFinalSP.Line &&
sp.Column == this.BodyFinalSP.Column &&
sp.Offset < this.BodyFinalSP.Offset) {
this.SequencePoints.Remove(this.BodyFinalSP); // remove duplicate
if (this.FileNameExt == ".cs") {
for (int i = this.SequencePoints.Count-1; i > 0; i--) {
var sp = this.SequencePoints[i];
if (sp.FileID != this.FileID) continue;
if (sp.Content != "}") continue;
if (this.BodyFinalSP == null || (sp.Line > this.BodyFinalSP.Line) ||
(sp.Line == this.BodyFinalSP.Line && sp.Column >= this.BodyFinalSP.Column)
) {
// ccrewrite ContractClass/ContractClassFor
// adds duplicate method end-sequence-point "}"
//
// Take duplicate BodyFinalSP with lower Offset
// Because IL.Offset of second duplicate
// will extend branch coverage of this method
// by coverage of ContractClassFor inserted SequencePoint!
if (this.BodyFinalSP != null &&
sp.Line == this.BodyFinalSP.Line &&
sp.Column == this.BodyFinalSP.Column &&
sp.Offset < this.BodyFinalSP.Offset) {
this.SequencePoints.Remove(this.BodyFinalSP); // remove duplicate
}
this.BodyFinalSP = sp;
}
this.BodyFinalSP = sp;
}
}
else {
this.BodyFinalSP = this.SequencePoints.Last();
}
}
}
@ -273,6 +289,9 @@ namespace ICSharpCode.CodeCoverage @@ -273,6 +289,9 @@ namespace ICSharpCode.CodeCoverage
return 0;
}
const string @assert = "Assert";
const string @contract = "Contract";
void GetBranchRatio () {
this.BranchCoverageRatio = null;
@ -295,31 +314,33 @@ namespace ICSharpCode.CodeCoverage @@ -295,31 +314,33 @@ namespace ICSharpCode.CodeCoverage
// SequencePoint is visited and belongs to this method?
if (sp.VisitCount != 0 && sp.FileID == this.FileID) {
// Don't want branch coverage of ccrewrite(n)
// SequencePoint's with offset before and after method body
if (sp.Offset < BodyStartSP.Offset ||
sp.Offset > BodyFinalSP.Offset) {
sp.BranchCoverage = true;
continue; // skip
}
if (this.FileNameExt == ".cs") {
// Only for C#
// 1) Generated "in" code for IEnumerables contains hidden "try/catch/finally" branches that
// one do not want or cannot cover by test-case because is handled earlier at same method.
// ie: NullReferenceException in foreach loop is pre-handled at method entry, ie. by Contract.Require(items!=null)
// 2) Branches within sequence points "{" and "}" are not source branches but compiler generated branches
// ie: static methods start sequence point "{" contains compiler generated branches
// 3) Exclude Contract class (EnsuresOnThrow/Assert/Assume is inside method body)
// 4) Exclude NUnit Assert(.Throws) class
const string assert = "Assert";
const string contract = "Contract";
if (sp.Content == "in" || sp.Content == "{" || sp.Content == "}" ||
sp.Content.StartsWith(assert + ".", StringComparison.Ordinal) ||
sp.Content.StartsWith(assert + " ", StringComparison.Ordinal) ||
sp.Content.StartsWith(contract + ".", StringComparison.Ordinal) ||
sp.Content.StartsWith(contract + " ", StringComparison.Ordinal)
) {
sp.BranchCoverage = true;
continue; // skip
// Don't want branch coverage of ccrewrite(n)
// SequencePoint(s) with offset before and after method body
if (sp.Offset < BodyStartSP.Offset ||
sp.Offset > BodyFinalSP.Offset) {
sp.BranchCoverage = true;
continue; // skip
}
// 1) Generated "in" code for IEnumerables contains hidden "try/catch/finally" branches that
// one do not want or cannot cover by test-case because is handled earlier at same method.
// ie: NullReferenceException in foreach loop is pre-handled at method entry, ie. by Contract.Require(items!=null)
// 2) Branches within sequence points "{" and "}" are not source branches but compiler generated branches
// ie: static methods start sequence point "{" contains compiler generated branches
// 3) Exclude Contract class (EnsuresOnThrow/Assert/Assume is inside method body)
// 4) Exclude NUnit Assert(.Throws) class
if (sp.Content == "in" || sp.Content == "{" || sp.Content == "}" ||
sp.Content.StartsWith(@assert + ".", StringComparison.Ordinal) ||
sp.Content.StartsWith(@assert + " ", StringComparison.Ordinal) ||
sp.Content.StartsWith(@contract + ".", StringComparison.Ordinal) ||
sp.Content.StartsWith(@contract + " ", StringComparison.Ordinal)
) {
sp.BranchCoverage = true;
continue; // skip
}
}
totalBranchCount += sp.BranchExitsCount;

20
src/AddIns/BackendBindings/CSharpBinding/Project/CSharpBinding.addin

@ -179,12 +179,9 @@ @@ -179,12 +179,9 @@
<Class class = "CSharpBinding.Refactoring.CSharpSyntaxIssue" />
<Class class = "CSharpBinding.Refactoring.SDRedundantUsingIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.BaseMethodCallWithDefaultParameterIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.AccessToDisposedClosureIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.AccessToModifiedClosureIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.AccessToStaticMemberViaDerivedTypeIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.AdditionalOfTypeIssues" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ArrayCreationCanBeReplacedWithArrayInitializerIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.AutoAsyncIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.BaseMemberHasParamsIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.BaseMethodParameterNameMismatchIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.BitwiseOperatorOnEnumWithoutFlagsIssue" />
@ -224,11 +221,8 @@ @@ -224,11 +221,8 @@
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.CS1717AssignmentMadeToSameVariableIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.CS1729TypeHasNoConstructorWithNArgumentsIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.DelegateSubtractionIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.DisposeMethodInNonIDisposableTypeIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.DoNotCallOverridableMethodsInConstructorIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.DontUseLinqWhenItsVerboseAndInefficientIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.DoubleNegationOperatorIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.DuplicatedLinqToListOrArrayIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.EmptyConstructorIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.EmptyDestructorIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.EmptyEmbeddedStatementIssue" />
@ -248,7 +242,6 @@ @@ -248,7 +242,6 @@
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ForStatementConditionIsTrueIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.FunctionNeverReturnsIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.InconsistentNamingIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.IncorrectCallToObjectGetHashCodeIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.InvokeAsExtensionMethodIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.LocalVariableHidesMemberIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.LocalVariableNotUsedIssue" />
@ -283,7 +276,6 @@ @@ -283,7 +276,6 @@
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantAttributeParenthesesIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantBaseConstructorCallIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantBaseQualifierIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantBlockInDifferentBranchesIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantBoolCompareIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantCaseLabelIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantCatchClauseIssue" />
@ -305,7 +297,6 @@ @@ -305,7 +297,6 @@
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantLambdaSignatureParenthesesIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantLogicalConditionalExpressionOperandIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantNameQualifierIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantNotNullAttributeInNonNullableTypeIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantObjectCreationArgumentListIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantObjectOrCollectionInitializerIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RedundantOverridenMemberIssue" />
@ -334,18 +325,20 @@ @@ -334,18 +325,20 @@
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithOfTypeWhereIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSimpleAssignmentIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToAnyIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToAverageIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToCountIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToFirstIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToFirstOrDefaultIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToLastIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToLastOrDefaultIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToLongCountIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToMinIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToMaxIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToSingleIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToSingleOrDefaultIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithSingleCallToSumIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ReplaceWithStringIsNullOrEmptyIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ResultOfAsyncCallShouldNotBeIgnoredIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.RewriteIfReturnToReturnIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.SameGuardConditionExpressionInIfelseBranchesIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.SealedMemberInSealedClassIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.SimplifyConditionalTernaryExpressionIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.SimplifyLinqExpressionIssue" />
@ -361,7 +354,6 @@ @@ -361,7 +354,6 @@
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.SuggestUseVarKeywordEvidentIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.ThreadStaticAtInstanceFieldIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.UnassignedReadonlyFieldIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.UnmatchedSizeSpecificationInArrayCreationIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.UnreachableCodeIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.UnusedAnonymousMethodSignatureIssue" />
<Class class = "ICSharpCode.NRefactory.CSharp.Refactoring.UnusedLabelIssue" />
@ -510,7 +502,7 @@ @@ -510,7 +502,7 @@
<!-- Autostart command for initialization -->
<Path name = "/SharpDevelop/Autostart">
<Class id = "CSharpFormattingOptionsPersistenceInitCommand"
class = "CSharpBinding.FormattingStrategy.CSharpFormattingOptionsPersistenceInitCommand"/>
<Class id = "CSharpFormattingOptionsPoliciesInitCommand"
class = "CSharpBinding.FormattingStrategy.CSharpFormattingOptionsPoliciesInitCommand"/>
</Path>
</AddIn>

2
src/AddIns/BackendBindings/CSharpBinding/Project/CSharpBinding.csproj

@ -93,7 +93,7 @@ @@ -93,7 +93,7 @@
</Compile>
<Compile Include="Src\FormattingStrategy\CSharpFormattingOptionsContainer.cs" />
<Compile Include="Src\FormattingStrategy\CSharpFormatter.cs" />
<Compile Include="Src\FormattingStrategy\CSharpFormattingOptionsPersistence.cs" />
<Compile Include="Src\FormattingStrategy\CSharpFormattingPolicies.cs" />
<Compile Include="Src\FormattingStrategy\FormattingOptionBinding.cs" />
<Compile Include="Src\FormsDesigner\CSharpDesignerGenerator.cs" />
<Compile Include="Src\FormsDesigner\CSharpDesignerLoader.cs" />

259
src/AddIns/BackendBindings/CSharpBinding/Project/Src/CSharpLanguageBinding.cs

@ -19,7 +19,9 @@ @@ -19,7 +19,9 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Threading;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Highlighting;
using ICSharpCode.NRefactory;
using ICSharpCode.NRefactory.TypeSystem;
@ -62,6 +64,8 @@ namespace CSharpBinding @@ -62,6 +64,8 @@ namespace CSharpBinding
IList<IContextActionProvider> contextActionProviders;
CodeManipulation codeManipulation;
CaretReferenceHighlightRenderer renderer;
CodeEditorFormattingOptionsAdapter options;
TextEditorOptions originalEditorOptions;
public void Attach(ITextEditor editor)
{
@ -70,14 +74,46 @@ namespace CSharpBinding @@ -70,14 +74,46 @@ namespace CSharpBinding
codeManipulation = new CodeManipulation(editor);
renderer = new CaretReferenceHighlightRenderer(editor);
// Patch editor options (indentation) to project-specific settings
if (!editor.ContextActionProviders.IsReadOnly) {
contextActionProviders = AddInTree.BuildItems<IContextActionProvider>("/SharpDevelop/ViewContent/TextEditor/C#/ContextActions", null);
editor.ContextActionProviders.AddRange(contextActionProviders);
}
// Create instance of options adapter and register it as service
var formattingPolicy = CSharpFormattingPolicies.Instance.GetProjectOptions(
SD.ProjectService.FindProjectContainingFile(editor.FileName));
options = new CodeEditorFormattingOptionsAdapter(editor.Options, formattingPolicy.OptionsContainer);
var textEditor = editor.GetService<TextEditor>();
if (textEditor != null) {
var textViewServices = textEditor.TextArea.TextView.Services;
// Unregister any previous ITextEditorOptions instance from editor, if existing, register our impl.
textViewServices.RemoveService(typeof(ITextEditorOptions));
textViewServices.AddService(typeof(ITextEditorOptions), options);
// Set TextEditor's options to same object
originalEditorOptions = textEditor.Options;
textEditor.Options = options;
}
}
public void Detach()
{
var textEditor = editor.GetService<TextEditor>();
if (textEditor != null) {
var textView = textEditor.TextArea.TextView;
// Unregister our ITextEditorOptions instance from editor
var optionsService = textView.GetService<ITextEditorOptions>();
if ((optionsService != null) && (optionsService == options))
textView.Services.RemoveService(typeof(ITextEditorOptions));
// Reset TextEditor options, too?
if ((textEditor.Options != null) && (textEditor.Options == options))
textEditor.Options = originalEditorOptions;
}
codeManipulation.Dispose();
if (inspectionManager != null) {
inspectionManager.Dispose();
@ -87,7 +123,230 @@ namespace CSharpBinding @@ -87,7 +123,230 @@ namespace CSharpBinding
editor.ContextActionProviders.RemoveAll(contextActionProviders.Contains);
}
renderer.Dispose();
options = null;
this.editor = null;
}
}
class CodeEditorFormattingOptionsAdapter : TextEditorOptions, ITextEditorOptions, ICodeEditorOptions
{
CSharpFormattingOptionsContainer container;
readonly ITextEditorOptions globalOptions;
readonly ICodeEditorOptions globalCodeEditorOptions;
public CodeEditorFormattingOptionsAdapter(ITextEditorOptions globalOptions, CSharpFormattingOptionsContainer container)
{
if (globalOptions == null)
throw new ArgumentNullException("globalOptions");
if (container == null)
throw new ArgumentNullException("container");
this.globalOptions = globalOptions;
this.globalCodeEditorOptions = globalOptions as ICodeEditorOptions;
this.container = container;
CSharpFormattingPolicies.Instance.FormattingPolicyUpdated += OnFormattingPolicyUpdated;
globalOptions.PropertyChanged += OnGlobalOptionsPropertyChanged;
}
void OnFormattingPolicyUpdated(object sender, CSharpBinding.FormattingStrategy.CSharpFormattingPolicyUpdateEventArgs e)
{
OnPropertyChanged("IndentationSize");
OnPropertyChanged("ConvertTabsToSpaces");
}
void OnGlobalOptionsPropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
OnPropertyChanged(e.PropertyName);
}
#region ITextEditorOptions implementation
public override int IndentationSize {
get {
return container.GetEffectiveIndentationSize() ?? globalOptions.IndentationSize;
}
}
public override bool ConvertTabsToSpaces {
get {
return container.GetEffectiveConvertTabsToSpaces() ?? globalOptions.ConvertTabsToSpaces;
}
}
public bool AutoInsertBlockEnd {
get {
return globalOptions.AutoInsertBlockEnd;
}
}
public int VerticalRulerColumn {
get {
return globalOptions.VerticalRulerColumn;
}
}
public bool UnderlineErrors {
get {
return globalOptions.UnderlineErrors;
}
}
public string FontFamily {
get {
return globalOptions.FontFamily;
}
}
public double FontSize {
get {
return globalOptions.FontSize;
}
}
#endregion
public override bool AllowScrollBelowDocument {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.AllowScrollBelowDocument : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.AllowScrollBelowDocument = value;
}
}
}
public bool ShowLineNumbers {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.ShowLineNumbers : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.ShowLineNumbers = value;
}
}
}
public bool EnableChangeMarkerMargin {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.EnableChangeMarkerMargin : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.EnableChangeMarkerMargin = value;
}
}
}
public bool WordWrap {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.WordWrap : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.WordWrap = value;
}
}
}
public bool CtrlClickGoToDefinition {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.CtrlClickGoToDefinition : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.CtrlClickGoToDefinition = value;
}
}
}
public bool MouseWheelZoom {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.MouseWheelZoom : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.MouseWheelZoom = value;
}
}
}
public bool HighlightBrackets {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.HighlightBrackets : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.HighlightBrackets = value;
}
}
}
public bool HighlightSymbol {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.HighlightSymbol : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.HighlightSymbol = value;
}
}
}
public bool EnableAnimations {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.EnableAnimations : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.EnableAnimations = value;
}
}
}
public bool UseSmartIndentation {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.UseSmartIndentation : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.UseSmartIndentation = value;
}
}
}
public bool EnableFolding {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.EnableFolding : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.EnableFolding = value;
}
}
}
public bool EnableQuickClassBrowser {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.EnableQuickClassBrowser : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.EnableQuickClassBrowser = value;
}
}
}
public bool ShowHiddenDefinitions {
get {
return (globalCodeEditorOptions != null) ? globalCodeEditorOptions.ShowHiddenDefinitions : default(bool);
}
set {
if (globalCodeEditorOptions != null) {
globalCodeEditorOptions.ShowHiddenDefinitions = value;
}
}
}
}
}

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpCompletionBinding.cs

@ -99,7 +99,7 @@ namespace CSharpBinding.Completion @@ -99,7 +99,7 @@ namespace CSharpBinding.Completion
completionContext.ProjectContent,
completionContext.TypeResolveContextAtCaret
);
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(completionContext.Compilation.GetProject());
var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(completionContext.Compilation.GetProject());
cce.FormattingPolicy = formattingOptions.OptionsContainer.GetEffectiveOptions();
cce.EolMarker = DocumentUtilities.GetLineTerminator(completionContext.Document, currentLocation.Line);

1
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpCompletionContext.cs

@ -90,6 +90,7 @@ namespace CSharpBinding.Completion @@ -90,6 +90,7 @@ namespace CSharpBinding.Completion
this.ProjectContent = projectContent;
this.TypeResolveContextAtCaret = parseInfo.UnresolvedFile.GetTypeResolveContext(compilation, caretLocation);
this.CompletionContextProvider = new DefaultCompletionContextProvider(document, parseInfo.UnresolvedFile);
this.CompletionContextProvider.ConditionalSymbols.AddRange(parseInfo.SyntaxTree.ConditionalSymbols);
}
}
}

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpInsightItem.cs

@ -72,7 +72,7 @@ namespace CSharpBinding.Completion @@ -72,7 +72,7 @@ namespace CSharpBinding.Completion
ambience.ConversionFlags = ConversionFlags.StandardConversionFlags;
var stringBuilder = new StringBuilder();
var formatter = new ParameterHighlightingOutputFormatter(stringBuilder, highlightedParameterIndex);
ambience.ConvertSymbol(Method, formatter, CSharpFormattingOptionsPersistence.GlobalOptions.OptionsContainer.GetEffectiveOptions());
ambience.ConvertSymbol(Method, formatter, CSharpFormattingPolicies.Instance.GlobalOptions.OptionsContainer.GetEffectiveOptions());
var documentation = XmlDocumentationElement.Get(Method);
ambience.ConversionFlags = ConversionFlags.ShowTypeParameterList;

4
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/CSharpMethodInsight.cs

@ -50,7 +50,9 @@ namespace CSharpBinding.Completion @@ -50,7 +50,9 @@ namespace CSharpBinding.Completion
public void Show()
{
window = editor.ShowInsightWindow(items);
window.StartOffset = startOffset;
// Set startOffset so that window always appears below the caret line
var startLocation = editor.Document.GetLocation(startOffset);
window.StartOffset = editor.Document.GetOffset(editor.Caret.Line, startLocation.Column);
// closing the window at the end of the parameter list is handled by the CaretPositionChanged event
window.EndOffset = editor.Document.TextLength;
if (initiallySelectedItem != null)

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/OverrideCompletionData.cs

@ -98,7 +98,7 @@ namespace CSharpBinding.Completion @@ -98,7 +98,7 @@ namespace CSharpBinding.Completion
var document = context.Editor.Document;
StringWriter w = new StringWriter();
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(contextAtCaret.Compilation.GetProject());
var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(contextAtCaret.Compilation.GetProject());
var segmentDict = SegmentTrackingOutputFormatter.WriteNode(
w, entityDeclaration, formattingOptions.OptionsContainer.GetEffectiveOptions(), context.Editor.Options);

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/OverrideEqualsGetHashCodeCompletionData.cs

@ -84,7 +84,7 @@ namespace CSharpBinding.Completion @@ -84,7 +84,7 @@ namespace CSharpBinding.Completion
var document = context.Editor.Document;
StringWriter w = new StringWriter();
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(contextAtCaret.Compilation.GetProject());
var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(contextAtCaret.Compilation.GetProject());
var segmentDict = SegmentTrackingOutputFormatter.WriteNode(
w, entityDeclaration, formattingOptions.OptionsContainer.GetEffectiveOptions(), context.Editor.Options);

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/OverrideToStringCompletionData.cs

@ -81,7 +81,7 @@ namespace CSharpBinding.Completion @@ -81,7 +81,7 @@ namespace CSharpBinding.Completion
var document = context.Editor.Document;
StringWriter w = new StringWriter();
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(contextAtCaret.Compilation.GetProject());
var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(contextAtCaret.Compilation.GetProject());
var segmentDict = SegmentTrackingOutputFormatter.WriteNode(
w, entityDeclaration, formattingOptions.OptionsContainer.GetEffectiveOptions(), context.Editor.Options);

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Completion/PartialCompletionData.cs

@ -64,7 +64,7 @@ namespace CSharpBinding.Completion @@ -64,7 +64,7 @@ namespace CSharpBinding.Completion
var document = context.Editor.Document;
StringWriter w = new StringWriter();
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(contextAtCaret.Compilation.GetProject());
var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(contextAtCaret.Compilation.GetProject());
var segmentDict = SegmentTrackingOutputFormatter.WriteNode(
w, entityDeclaration, formattingOptions.OptionsContainer.GetEffectiveOptions(), context.Editor.Options);

4
src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormatter.cs

@ -31,7 +31,9 @@ namespace CSharpBinding.FormattingStrategy @@ -31,7 +31,9 @@ namespace CSharpBinding.FormattingStrategy
/// </summary>
public static void Format(ITextEditor editor, int offset, int length, CSharpFormattingOptionsContainer optionsContainer)
{
var formatter = new CSharpFormatter(optionsContainer.GetEffectiveOptions(), editor.ToEditorOptions());
TextEditorOptions editorOptions = editor.ToEditorOptions();
optionsContainer.CustomizeEditorOptions(editorOptions);
var formatter = new CSharpFormatter(optionsContainer.GetEffectiveOptions(), editorOptions);
formatter.AddFormattingRegion(new DomRegion(editor.Document.GetLocation(offset), editor.Document.GetLocation(offset + length)));
var changes = formatter.AnalyzeFormatting(editor.Document, SyntaxTree.Parse(editor.Document));
changes.ApplyChanges(offset, length);

150
src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormattingOptionsContainer.cs

@ -34,8 +34,13 @@ namespace CSharpBinding.FormattingStrategy @@ -34,8 +34,13 @@ namespace CSharpBinding.FormattingStrategy
/// </summary>
internal class CSharpFormattingOptionsContainer : INotifyPropertyChanged
{
private const string IndentationSizePropertyName = "IndentationSize";
private const string ConvertTabsToSpacesPropertyName = "ConvertTabsToSpaces";
CSharpFormattingOptionsContainer parent;
CSharpFormattingOptions cachedOptions;
int? indentationSize;
bool? convertTabsToSpaces;
readonly HashSet<string> activeOptions;
@ -106,6 +111,8 @@ namespace CSharpBinding.FormattingStrategy @@ -106,6 +111,8 @@ namespace CSharpBinding.FormattingStrategy
foreach (var activeOption in options.activeOptions)
activeOptions.Add(activeOption);
cachedOptions = options.cachedOptions.Clone();
indentationSize = options.indentationSize;
convertTabsToSpaces = options.convertTabsToSpaces;
OnPropertyChanged(null);
}
@ -127,6 +134,14 @@ namespace CSharpBinding.FormattingStrategy @@ -127,6 +134,14 @@ namespace CSharpBinding.FormattingStrategy
if ((e.PropertyName == "Parent") || (e.PropertyName == null)) {
// All properties might have changed -> update everything
cachedOptions = CreateCachedOptions();
} else if (e.PropertyName == IndentationSizePropertyName) {
if (!indentationSize.HasValue) {
indentationSize = GetEffectiveIndentationSize();
}
} else if (e.PropertyName == ConvertTabsToSpacesPropertyName) {
if (!convertTabsToSpaces.HasValue) {
convertTabsToSpaces = GetEffectiveConvertTabsToSpaces();
}
} else {
// Some other property has changed, check if we have our own value for it
if (!activeOptions.Contains(e.PropertyName)) {
@ -148,10 +163,18 @@ namespace CSharpBinding.FormattingStrategy @@ -148,10 +163,18 @@ namespace CSharpBinding.FormattingStrategy
public object GetOption(string option)
{
// Run up the hierarchy until we find a defined value for property
if (activeOptions.Contains(option)) {
PropertyInfo propertyInfo = typeof(CSharpFormattingOptions).GetProperty(option);
if (propertyInfo != null) {
return propertyInfo.GetValue(cachedOptions);
if (option == IndentationSizePropertyName) {
if (indentationSize.HasValue)
return indentationSize.Value;
} else if (option == ConvertTabsToSpacesPropertyName) {
if (convertTabsToSpaces.HasValue)
return convertTabsToSpaces.Value;
} else {
if (activeOptions.Contains(option)) {
PropertyInfo propertyInfo = typeof(CSharpFormattingOptions).GetProperty(option);
if (propertyInfo != null) {
return propertyInfo.GetValue(cachedOptions);
}
}
}
@ -186,6 +209,68 @@ namespace CSharpBinding.FormattingStrategy @@ -186,6 +209,68 @@ namespace CSharpBinding.FormattingStrategy
return null;
}
public int? IndentationSize
{
get {
return indentationSize;
}
set {
indentationSize = value;
OnPropertyChanged(IndentationSizePropertyName);
}
}
/// <summary>
/// Retrieves the value of "IndentationSize" option by looking at current and (if nothing set here) parent
/// containers.
/// </summary>
public int? GetEffectiveIndentationSize()
{
// Run up the hierarchy until we find a defined value for property
CSharpFormattingOptionsContainer container = this;
do
{
int? val = container.indentationSize;
if (val.HasValue) {
return val.Value;
}
container = container.parent;
} while (container != null);
return null;
}
public bool? ConvertTabsToSpaces
{
get {
return convertTabsToSpaces;
}
set {
convertTabsToSpaces = value;
OnPropertyChanged(ConvertTabsToSpacesPropertyName);
}
}
/// <summary>
/// Retrieves the value of v option by looking at current and (if nothing set here) parent
/// containers.
/// </summary>
public bool? GetEffectiveConvertTabsToSpaces()
{
// Run up the hierarchy until we find a defined value for property
CSharpFormattingOptionsContainer container = this;
do
{
bool? val = container.convertTabsToSpaces;
if (val.HasValue) {
return val.Value;
}
container = container.parent;
} while (container != null);
return null;
}
/// <summary>
/// Sets an option.
/// </summary>
@ -195,18 +280,32 @@ namespace CSharpBinding.FormattingStrategy @@ -195,18 +280,32 @@ namespace CSharpBinding.FormattingStrategy
{
if (value != null) {
// Save value in option values and cached options
activeOptions.Add(option);
PropertyInfo propertyInfo = typeof(CSharpFormattingOptions).GetProperty(option);
if ((propertyInfo != null) && (propertyInfo.PropertyType == value.GetType())) {
propertyInfo.SetValue(cachedOptions, value);
if (option == IndentationSizePropertyName) {
if (value is int)
indentationSize = (int) value;
} else if (option == ConvertTabsToSpacesPropertyName) {
if (value is bool)
convertTabsToSpaces = (bool) value;
} else {
activeOptions.Add(option);
PropertyInfo propertyInfo = typeof(CSharpFormattingOptions).GetProperty(option);
if ((propertyInfo != null) && (propertyInfo.PropertyType == value.GetType())) {
propertyInfo.SetValue(cachedOptions, value);
}
}
} else {
// Reset this option
activeOptions.Remove(option);
// Update formatting options object from parents
PropertyInfo propertyInfo = typeof(CSharpFormattingOptions).GetProperty(option);
if (propertyInfo != null) {
propertyInfo.SetValue(cachedOptions, GetEffectiveOption(option));
if (option == IndentationSizePropertyName) {
indentationSize = null;
} else if (option == ConvertTabsToSpacesPropertyName) {
convertTabsToSpaces = null;
} else {
activeOptions.Remove(option);
// Update formatting options object from parents
PropertyInfo propertyInfo = typeof(CSharpFormattingOptions).GetProperty(option);
if (propertyInfo != null) {
propertyInfo.SetValue(cachedOptions, GetEffectiveOption(option));
}
}
}
OnPropertyChanged(option);
@ -219,6 +318,11 @@ namespace CSharpBinding.FormattingStrategy @@ -219,6 +318,11 @@ namespace CSharpBinding.FormattingStrategy
/// <returns>Option's type.</returns>
public Type GetOptionType(string option)
{
if (option == IndentationSizePropertyName)
return typeof(int);
if (option == ConvertTabsToSpacesPropertyName)
return typeof(bool);
PropertyInfo propertyInfo = typeof(CSharpFormattingOptions).GetProperty(option);
if (propertyInfo != null) {
return propertyInfo.PropertyType;
@ -258,6 +362,19 @@ namespace CSharpBinding.FormattingStrategy @@ -258,6 +362,19 @@ namespace CSharpBinding.FormattingStrategy
return outputOptions;
}
public void CustomizeEditorOptions(TextEditorOptions editorOptions)
{
int? indentationSize = GetEffectiveIndentationSize();
if (indentationSize.HasValue) {
editorOptions.IndentSize = indentationSize.Value;
editorOptions.TabSize = indentationSize.Value;
editorOptions.ContinuationIndent = indentationSize.Value;
}
bool? convertTabsToSpaces = GetEffectiveConvertTabsToSpaces();
if (convertTabsToSpaces.HasValue)
editorOptions.TabsToSpaces = convertTabsToSpaces.Value;
}
public void Load(Properties parentProperties)
{
if (parentProperties == null)
@ -275,6 +392,9 @@ namespace CSharpBinding.FormattingStrategy @@ -275,6 +392,9 @@ namespace CSharpBinding.FormattingStrategy
}
}
}
indentationSize = formatProperties.Get(IndentationSizePropertyName, new int?());
convertTabsToSpaces = formatProperties.Get(ConvertTabsToSpacesPropertyName, new bool?());
}
}
@ -291,6 +411,10 @@ namespace CSharpBinding.FormattingStrategy @@ -291,6 +411,10 @@ namespace CSharpBinding.FormattingStrategy
formatProperties.Set(activeOption, val);
}
}
if (indentationSize.HasValue)
formatProperties.Set(IndentationSizePropertyName, indentationSize.Value);
if (convertTabsToSpaces.HasValue)
formatProperties.Set(ConvertTabsToSpacesPropertyName, convertTabsToSpaces.Value);
parentProperties.SetNestedProperties("CSharpFormatting", formatProperties);
}

128
src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormattingOptionsPersistence.cs → src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormattingPolicies.cs

@ -18,6 +18,7 @@ @@ -18,6 +18,7 @@
using System;
using System.Collections.Generic;
using System.ComponentModel;
using ICSharpCode.Core;
using ICSharpCode.NRefactory.CSharp;
using ICSharpCode.SharpDevelop;
@ -25,43 +26,50 @@ using ICSharpCode.SharpDevelop.Project; @@ -25,43 +26,50 @@ using ICSharpCode.SharpDevelop.Project;
namespace CSharpBinding.FormattingStrategy
{
public class CSharpFormattingOptionsPersistenceInitCommand : SimpleCommand
public class CSharpFormattingOptionsPoliciesInitCommand : SimpleCommand
{
public override void Execute(object parameter)
{
// Initialize CSharpFormattingOptionsPersistence as early as possible (before solution is opened)
CSharpFormattingOptionsPersistence.Initialize();
// Initialize CSharpFormattingPolicies as early as possible (before solution is opened)
CSharpFormattingPolicies.Instance.Initialize();
}
}
/// <summary>
/// Persistence helper for C# formatting options.
/// Management class for formatting policies.
/// </summary>
internal class CSharpFormattingOptionsPersistence
internal class CSharpFormattingPolicies
{
static bool initialized;
static Dictionary<string, CSharpFormattingOptionsPersistence> projectOptions;
static readonly Lazy<CSharpFormattingPolicies> LazyInstance =
new Lazy<CSharpFormattingPolicies>(() => new CSharpFormattingPolicies());
static CSharpFormattingOptionsPersistence()
public static CSharpFormattingPolicies Instance {
get { return LazyInstance.Value; }
}
public event EventHandler<CSharpFormattingPolicyUpdateEventArgs> FormattingPolicyUpdated;
bool initialized;
Dictionary<string, CSharpFormattingPolicy> projectOptions;
public CSharpFormattingPolicies()
{
Initialize();
// Load global settings
GlobalOptions = new CSharpFormattingPolicy(
SD.PropertyService.MainPropertiesContainer, new CSharpFormattingOptionsContainer() {
DefaultText = StringParser.Parse("${res:CSharpBinding.Formatting.GlobalOptionReference}")
});
GlobalOptions.FormattingPolicyUpdated += OnFormattingPolicyUpdated;
GlobalOptions.Load();
}
public static void Initialize()
public void Initialize()
{
if (initialized)
return;
initialized = true;
projectOptions = new Dictionary<string, CSharpFormattingOptionsPersistence>();
// Load global settings
GlobalOptions = new CSharpFormattingOptionsPersistence(
SD.PropertyService.MainPropertiesContainer, new CSharpFormattingOptionsContainer()
{
DefaultText = StringParser.Parse("${res:CSharpBinding.Formatting.GlobalOptionReference}")
});
GlobalOptions.Load();
projectOptions = new Dictionary<string, CSharpFormattingPolicy>();
// Handlers for solution loading/unloading
var projectService = SD.GetService<IProjectService>();
@ -71,8 +79,7 @@ namespace CSharpBinding.FormattingStrategy @@ -71,8 +79,7 @@ namespace CSharpBinding.FormattingStrategy
}
}
public static bool AutoFormatting
{
public static bool AutoFormatting {
get {
return SD.PropertyService.Get("CSharpBinding.Formatting.AutoFormatting", false);
}
@ -81,31 +88,32 @@ namespace CSharpBinding.FormattingStrategy @@ -81,31 +88,32 @@ namespace CSharpBinding.FormattingStrategy
}
}
public static CSharpFormattingOptionsPersistence GlobalOptions
{
public CSharpFormattingPolicy GlobalOptions {
get;
private set;
}
public static CSharpFormattingOptionsPersistence SolutionOptions
{
public CSharpFormattingPolicy SolutionOptions {
get;
private set;
}
public static CSharpFormattingOptionsPersistence GetProjectOptions(IProject project)
public CSharpFormattingPolicy GetProjectOptions(IProject project)
{
if (!initialized)
return GlobalOptions;
var csproject = project as CSharpProject;
if (csproject != null) {
string key = project.FileName;
if (!projectOptions.ContainsKey(key)) {
// Lazily create options container for project
var projectFormattingPersistence = new CSharpFormattingOptionsPersistence(
var projectFormattingPersistence = new CSharpFormattingPolicy(
csproject.GlobalPreferences,
new CSharpFormattingOptionsContainer((SolutionOptions ?? GlobalOptions).OptionsContainer)
{
new CSharpFormattingOptionsContainer((SolutionOptions ?? GlobalOptions).OptionsContainer) {
DefaultText = StringParser.Parse("${res:CSharpBinding.Formatting.ProjectOptionReference}")
});
projectFormattingPersistence.FormattingPolicyUpdated += OnFormattingPolicyUpdated;
projectFormattingPersistence.Load();
projectOptions[key] = projectFormattingPersistence;
}
@ -116,34 +124,70 @@ namespace CSharpBinding.FormattingStrategy @@ -116,34 +124,70 @@ namespace CSharpBinding.FormattingStrategy
return SolutionOptions ?? GlobalOptions;
}
static void SolutionOpened(object sender, SolutionEventArgs e)
void SolutionOpened(object sender, SolutionEventArgs e)
{
// Load solution settings
SolutionOptions = new CSharpFormattingOptionsPersistence(
SolutionOptions = new CSharpFormattingPolicy(
e.Solution.SDSettings,
new CSharpFormattingOptionsContainer(GlobalOptions.OptionsContainer)
{
new CSharpFormattingOptionsContainer(GlobalOptions.OptionsContainer) {
DefaultText = StringParser.Parse("${res:CSharpBinding.Formatting.SolutionOptionReference}")
});
SolutionOptions.FormattingPolicyUpdated += OnFormattingPolicyUpdated;
SolutionOptions.Load();
}
static void SolutionClosed(object sender, SolutionEventArgs e)
void SolutionClosed(object sender, SolutionEventArgs e)
{
SolutionOptions.FormattingPolicyUpdated -= OnFormattingPolicyUpdated;
SolutionOptions = null;
projectOptions.Clear();
}
void OnFormattingPolicyUpdated(object sender, CSharpFormattingPolicyUpdateEventArgs e)
{
if (FormattingPolicyUpdated != null) {
FormattingPolicyUpdated(sender, e);
}
}
}
/// <summary>
/// Contains event data for formatting policy update events.
/// </summary>
internal class CSharpFormattingPolicyUpdateEventArgs : EventArgs
{
public CSharpFormattingPolicyUpdateEventArgs(CSharpFormattingOptionsContainer container)
{
OptionsContainer = container;
}
/// <summary>
/// Returns updated options container.
/// </summary>
public CSharpFormattingOptionsContainer OptionsContainer
{
get;
private set;
}
}
/// <summary>
/// Persistence helper for C# formatting options of a certain policy (e.g. global, solution, project).
/// </summary>
internal class CSharpFormattingPolicy
{
public event EventHandler<CSharpFormattingPolicyUpdateEventArgs> FormattingPolicyUpdated;
readonly Properties propertiesContainer;
CSharpFormattingOptionsContainer optionsContainer;
readonly CSharpFormattingOptionsContainer optionsContainer;
CSharpFormattingOptionsContainer optionsContainerWorkingCopy;
/// <summary>
/// Creates a new instance of formatting options persistence helper, using given options to predefine the options container.
/// Creates a new instance of formatting options policy, using given options to predefine the options container.
/// </summary>
/// <param name="propertiesContainer">Properties container to load from and save to.</param>
/// <param name="initialContainer">Initial (empty) instance of formatting options container.</param>
public CSharpFormattingOptionsPersistence(Properties propertiesContainer, CSharpFormattingOptionsContainer initialContainer)
public CSharpFormattingPolicy(Properties propertiesContainer, CSharpFormattingOptionsContainer initialContainer)
{
if (initialContainer == null)
throw new ArgumentNullException("initialContainer");
@ -153,7 +197,7 @@ namespace CSharpBinding.FormattingStrategy @@ -153,7 +197,7 @@ namespace CSharpBinding.FormattingStrategy
}
/// <summary>
/// Returns the option container managed by this helper.
/// Returns the option container for this policy.
/// </summary>
public CSharpFormattingOptionsContainer OptionsContainer
{
@ -196,7 +240,15 @@ namespace CSharpBinding.FormattingStrategy @@ -196,7 +240,15 @@ namespace CSharpBinding.FormattingStrategy
// Convert to SD properties
optionsContainer.Save(propertiesContainer);
OnFormattingPolicyUpdated(this, optionsContainer);
return true;
}
void OnFormattingPolicyUpdated(object sender, CSharpFormattingOptionsContainer container)
{
if (FormattingPolicyUpdated != null) {
FormattingPolicyUpdated(sender, new CSharpFormattingPolicyUpdateEventArgs(container));
}
}
}
}

74
src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/CSharpFormattingStrategy.cs

@ -48,7 +48,7 @@ namespace CSharpBinding.FormattingStrategy @@ -48,7 +48,7 @@ namespace CSharpBinding.FormattingStrategy
DocumentAccessor acc = new DocumentAccessor(editor.Document, lineNr, lineNr);
CSharpIndentationStrategy indentStrategy = new CSharpIndentationStrategy();
indentStrategy.IndentationString = editor.Options.IndentationString;
indentStrategy.IndentationString = GetIndentationString(editor);
indentStrategy.Indent(acc, false);
string t = acc.Text;
@ -62,33 +62,67 @@ namespace CSharpBinding.FormattingStrategy @@ -62,33 +62,67 @@ namespace CSharpBinding.FormattingStrategy
{
DocumentAccessor acc = new DocumentAccessor(editor.Document, beginLine, endLine);
CSharpIndentationStrategy indentStrategy = new CSharpIndentationStrategy();
indentStrategy.IndentationString = editor.Options.IndentationString;
indentStrategy.IndentationString = GetIndentationString(editor);
indentStrategy.Indent(acc, true);
}
CSharpFormattingOptionsContainer GetOptionsContainerForEditor(ITextEditor editor)
{
var currentProject = SD.ProjectService.FindProjectContainingFile(editor.FileName);
if (currentProject != null) {
var persistence = CSharpFormattingPolicies.Instance.GetProjectOptions(currentProject);
if (persistence != null) {
return persistence.OptionsContainer;
}
}
return null;
}
string GetIndentationString(ITextEditor editor)
{
// Get current indentation option values
int indentationSize = editor.Options.IndentationSize;
bool convertTabsToSpaces = editor.Options.ConvertTabsToSpaces;
var container = GetOptionsContainerForEditor(editor);
if (container != null) {
int? effectiveIndentationSize = container.GetEffectiveIndentationSize();
if (effectiveIndentationSize.HasValue)
indentationSize = effectiveIndentationSize.Value;
bool? effectiveConvertTabsToSpaces = container.GetEffectiveConvertTabsToSpaces();
if (effectiveConvertTabsToSpaces.HasValue)
convertTabsToSpaces = effectiveConvertTabsToSpaces.Value;
}
if (convertTabsToSpaces)
return new string(' ', indentationSize);
else
return "\t";
}
/* NR indent engine (temporarily?) disabled as per #447
static void IndentSingleLine(CacheIndentEngine engine, IDocument document, IDocumentLine line)
{
engine.Update(line.EndOffset);
if (engine.NeedsReindent) {
var indentation = TextUtilities.GetWhitespaceAfter(document, line.Offset);
// replacing the indentation in two steps is necessary to make the caret move accordingly.
document.Replace(indentation.Offset, indentation.Length, "");
document.Replace(indentation.Offset, 0, engine.ThisLineIndent);
engine.ResetEngineToPosition(line.Offset);
}
engine.Update(line.EndOffset);
if (engine.NeedsReindent) {
var indentation = TextUtilities.GetWhitespaceAfter(document, line.Offset);
// replacing the indentation in two steps is necessary to make the caret move accordingly.
document.Replace(indentation.Offset, indentation.Length, "");
document.Replace(indentation.Offset, 0, engine.ThisLineIndent);
engine.ResetEngineToPosition(line.Offset);
}
}
static CacheIndentEngine CreateIndentEngine(IDocument document, TextEditorOptions options)
{
IProject currentProject = null;
var projectService = SD.GetService<IProjectService>();
if (projectService != null) {
currentProject = projectService.FindProjectContainingFile(new FileName(document.FileName));
}
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(currentProject);
var engine = new CSharpIndentEngine(document, options, formattingOptions.OptionsContainer.GetEffectiveOptions());
return new CacheIndentEngine(engine);
IProject currentProject = null;
var projectService = SD.GetService<IProjectService>();
if (projectService != null) {
currentProject = projectService.FindProjectContainingFile(new FileName(document.FileName));
}
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(currentProject);
var engine = new CSharpIndentEngine(document, options, formattingOptions.OptionsContainer.GetEffectiveOptions());
return new CacheIndentEngine(engine);
}
*/
#endregion
@ -302,11 +336,11 @@ namespace CSharpBinding.FormattingStrategy @@ -302,11 +336,11 @@ namespace CSharpBinding.FormattingStrategy
{
if ((offset > textArea.Document.TextLength) || ((offset + length) > textArea.Document.TextLength))
return false;
if (respectAutoFormattingSetting && !CSharpFormattingOptionsPersistence.AutoFormatting)
if (respectAutoFormattingSetting && !CSharpFormattingPolicies.AutoFormatting)
return false;
using (textArea.Document.OpenUndoGroup()) {
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(SD.ProjectService.CurrentProject);
var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(SD.ProjectService.CurrentProject);
try {
CSharpFormatterHelper.Format(textArea, offset, length, formattingOptions.OptionsContainer);
} catch (Exception) {

53
src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormattingStrategy/FormattingOptionBinding.cs

@ -22,6 +22,7 @@ using System.Windows; @@ -22,6 +22,7 @@ using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using ICSharpCode.NRefactory.CSharp;
using CSharpBinding.OptionPanels;
namespace CSharpBinding.FormattingStrategy
{
@ -32,11 +33,8 @@ namespace CSharpBinding.FormattingStrategy @@ -32,11 +33,8 @@ namespace CSharpBinding.FormattingStrategy
{
public static readonly DependencyProperty ContainerProperty =
DependencyProperty.RegisterAttached("Container", typeof(CSharpFormattingOptionsContainer),
typeof(FormattingOptionBinding),
new FrameworkPropertyMetadata());
public static readonly DependencyProperty OptionProperty =
DependencyProperty.RegisterAttached("Option", typeof(string), typeof(FormattingOptionBinding),
new FrameworkPropertyMetadata(OnOptionPropertyChanged));
typeof(FormattingOptionBinding),
new FrameworkPropertyMetadata((o, e) => UpdateOptionBinding(o)));
public static CSharpFormattingOptionsContainer GetContainer(Selector element)
{
@ -48,21 +46,26 @@ namespace CSharpBinding.FormattingStrategy @@ -48,21 +46,26 @@ namespace CSharpBinding.FormattingStrategy
element.SetValue(ContainerProperty, container);
}
public static string GetOption(Selector element)
public static readonly DependencyProperty FormattingOptionProperty =
DependencyProperty.RegisterAttached("FormattingOption", typeof(FormattingOption),
typeof(FormattingOptionBinding),
new FrameworkPropertyMetadata((o, e) => UpdateOptionBinding(o)));
public static FormattingOption GetFormattingOption(Selector element)
{
return (string) element.GetValue(OptionProperty);
return (FormattingOption) element.GetValue(FormattingOptionProperty);
}
public static void SetOption(Selector element, string option)
public static void SetFormattingOption(Selector element, FormattingOption container)
{
element.SetValue(OptionProperty, option);
element.SetValue(FormattingOptionProperty, container);
}
static void OnOptionPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
static void UpdateOptionBinding(DependencyObject o)
{
string option = e.NewValue as string;
ComboBox comboBox = o as ComboBox;
CSharpFormattingOptionsContainer container = GetContainer(comboBox);
FormattingOption option = GetFormattingOption(comboBox);
if ((option != null) && (comboBox != null) && (container != null)) {
if (container != null) {
if (container.Parent != null) {
@ -72,17 +75,24 @@ namespace CSharpBinding.FormattingStrategy @@ -72,17 +75,24 @@ namespace CSharpBinding.FormattingStrategy
Tag = null
});
comboBox.SelectedIndex = 0;
} else if (option.AlwaysAllowDefault) {
// Also add "default" entry, but without changeable text by container
comboBox.Items.Add(new ComboBoxItem {
Content = "(default)",
Tag = null
});
comboBox.SelectedIndex = 0;
}
Type optionType = container.GetOptionType(option);
Type optionType = container.GetOptionType(option.Option);
FillComboValues(comboBox, optionType);
UpdateComboBoxValue(container, option, comboBox);
UpdateComboBoxValue(container, option.Option, comboBox);
comboBox.SelectionChanged += ComboBox_SelectionChanged;
container.PropertyChanged += (sender, eventArgs) =>
{
if ((eventArgs.PropertyName == null) || (eventArgs.PropertyName == option))
UpdateComboBoxValue(container, option, comboBox);
if ((eventArgs.PropertyName == null) || (eventArgs.PropertyName == option.Option))
UpdateComboBoxValue(container, option.Option, comboBox);
};
}
}
@ -98,13 +108,13 @@ namespace CSharpBinding.FormattingStrategy @@ -98,13 +108,13 @@ namespace CSharpBinding.FormattingStrategy
{
ComboBox comboBox = sender as ComboBox;
if (comboBox != null) {
string option = GetOption(comboBox);
FormattingOption option = GetFormattingOption(comboBox);
CSharpFormattingOptionsContainer container = GetContainer(comboBox);
if ((container != null) && (option != null)) {
ComboBoxItem selectedItem = comboBox.SelectedItem as ComboBoxItem;
if (selectedItem != null) {
// Set option to appropriate value
container.SetOption(option, selectedItem.Tag);
container.SetOption(option.Option, selectedItem.Tag);
}
}
}
@ -140,11 +150,10 @@ namespace CSharpBinding.FormattingStrategy @@ -140,11 +150,10 @@ namespace CSharpBinding.FormattingStrategy
static void FillIntComboValues(ComboBox comboBox)
{
comboBox.Items.Add(new ComboBoxItem { Content = "0", Tag = 0 });
comboBox.Items.Add(new ComboBoxItem { Content = "1", Tag = 1 });
comboBox.Items.Add(new ComboBoxItem { Content = "2", Tag = 2 });
comboBox.Items.Add(new ComboBoxItem { Content = "3", Tag = 3 });
comboBox.Items.Add(new ComboBoxItem { Content = "4", Tag = 4 });
for (int i = 0; i < 11; i++)
{
comboBox.Items.Add(new ComboBoxItem { Content = i.ToString(), Tag = i });
}
}
static void FillBraceStyleComboValues(ComboBox comboBox)

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormsDesigner/CSharpDesignerGenerator.cs

@ -155,7 +155,7 @@ namespace CSharpBinding.FormsDesigner @@ -155,7 +155,7 @@ namespace CSharpBinding.FormsDesigner
IDocument document = context.GetDocument(fileNameObj);
var ctx = SDRefactoringContext.Create(fileNameObj, document);
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(compilation.GetProject());
var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(compilation.GetProject());
script = new DocumentScript(document, formattingOptions.OptionsContainer.GetEffectiveOptions(), new TextEditorOptions());
scripts.Add(fileNameObj, script);
return script;

3
src/AddIns/BackendBindings/CSharpBinding/Project/Src/FormsDesigner/SecondaryDisplayBinding.cs

@ -64,7 +64,8 @@ namespace CSharpBinding.FormsDesigner @@ -64,7 +64,8 @@ namespace CSharpBinding.FormsDesigner
foreach (var baseType in c.GetNonInterfaceBaseTypes()) {
var baseTypeName = baseType.FullName;
if (baseTypeName == "System.Windows.Forms.Form"
|| baseTypeName == "System.Windows.Forms.UserControl")
|| baseTypeName == "System.Windows.Forms.UserControl"
|| baseTypeName == "System.ComponentModel.Component")
{
return true;
}

36
src/AddIns/BackendBindings/CSharpBinding/Project/Src/OptionPanels/CSharpFormattingEditor.xaml

@ -274,13 +274,13 @@ @@ -274,13 +274,13 @@
<DataTemplate>
<Grid Margin="0,0,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*" />
<ColumnDefinition Width="*" MaxWidth="400" />
<ColumnDefinition Width="Auto" SharedSizeGroup="ComboBoxColumn" />
</Grid.ColumnDefinitions>
<ComboBox Grid.Column="1" Margin="0,0,0,0" MinWidth="100"
VerticalAlignment="Center"
format:FormattingOptionBinding.Container="{Binding ElementName=CSharpFormattingEditor_Self, Path=OptionsContainer}"
format:FormattingOptionBinding.Option="{Binding Option}" />
format:FormattingOptionBinding.FormattingOption="{Binding}" />
<sd:RestrictDesiredSize RestrictHeight="False" MinWidth="150">
<TextBlock Grid.Column="0"
Text="{Binding Text}"
@ -297,9 +297,39 @@ @@ -297,9 +297,39 @@
</UserControl.Resources>
<DockPanel>
<Grid DockPanel.Dock="Top"
Visibility="{Binding Path=OverrideGlobalIndentation, Converter={StaticResource boolToVisibilityConverter}}">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="Auto" />
</Grid.ColumnDefinitions>
<Grid.RowDefinitions>
<RowDefinition Height="Auto" />
<RowDefinition Height="Auto" />
</Grid.RowDefinitions>
<Label Grid.Column="0" Grid.Row="0"
Content="{core:Localize Dialog.Options.IDEOptions.TextEditor.Behaviour.IndentLabel}" />
<ComboBox Grid.Column="1" Grid.Row="0" MinWidth="100" Margin="0,0,0,3"
format:FormattingOptionBinding.Container="{Binding ElementName=CSharpFormattingEditor_Self, Path=OptionsContainer}">
<format:FormattingOptionBinding.FormattingOption>
<local:FormattingOption Option="IndentationSize" AlwaysAllowDefault="True" />
</format:FormattingOptionBinding.FormattingOption>
</ComboBox>
<Label Grid.Column="0" Grid.Row="1"
Content="{core:Localize Dialog.Options.IDEOptions.TextEditor.Behaviour.ConvertTabsToSpacesCheckBox}" />
<ComboBox Grid.Column="1" Grid.Row="1" MinWidth="100" Margin="0,0,0,3"
format:FormattingOptionBinding.Container="{Binding ElementName=CSharpFormattingEditor_Self, Path=OptionsContainer}">
<format:FormattingOptionBinding.FormattingOption>
<local:FormattingOption Option="ConvertTabsToSpaces" AlwaysAllowDefault="True" />
</format:FormattingOptionBinding.FormattingOption>
</ComboBox>
</Grid>
<Grid
Visibility="{Binding Path=AllowPresets, Converter={StaticResource boolToVisibilityConverter}}"
DockPanel.Dock="Top">
DockPanel.Dock="Top" Margin="0,5,0,0">
<Grid.ColumnDefinitions>
<ColumnDefinition Width="Auto" />
<ColumnDefinition Width="*" />

42
src/AddIns/BackendBindings/CSharpBinding/Project/Src/OptionPanels/CSharpFormattingEditor.xaml.cs

@ -29,21 +29,13 @@ using CSharpBinding.FormattingStrategy; @@ -29,21 +29,13 @@ using CSharpBinding.FormattingStrategy;
namespace CSharpBinding.OptionPanels
{
/// <summary>
/// Marker interface for group or option container.
/// It doesn't need to have any members.
/// </summary>
internal interface IFormattingItemContainer
{
}
/// <summary>
/// Represents a container item for other container items in formatting editor list
/// </summary>
[ContentProperty("Children")]
internal class FormattingGroupContainer : DependencyObject, IFormattingItemContainer
internal class FormattingGroupContainer : DependencyObject
{
readonly ObservableCollection<IFormattingItemContainer> children = new ObservableCollection<IFormattingItemContainer>();
readonly ObservableCollection<DependencyObject> children = new ObservableCollection<DependencyObject>();
public static readonly DependencyProperty TextProperty =
DependencyProperty.Register("Text", typeof(string), typeof(FormattingGroupContainer),
@ -54,7 +46,7 @@ namespace CSharpBinding.OptionPanels @@ -54,7 +46,7 @@ namespace CSharpBinding.OptionPanels
set { SetValue(TextProperty, value); }
}
public ObservableCollection<IFormattingItemContainer> Children
public ObservableCollection<DependencyObject> Children
{
get {
return children;
@ -66,7 +58,7 @@ namespace CSharpBinding.OptionPanels @@ -66,7 +58,7 @@ namespace CSharpBinding.OptionPanels
/// Represents a container for formatting options.
/// </summary>
[ContentProperty("Children")]
internal class FormattingOptionContainer : DependencyObject, IFormattingItemContainer
internal class FormattingOptionContainer : DependencyObject
{
readonly ObservableCollection<FormattingOption> children = new ObservableCollection<FormattingOption>();
@ -91,11 +83,26 @@ namespace CSharpBinding.OptionPanels @@ -91,11 +83,26 @@ namespace CSharpBinding.OptionPanels
set { SetValue(TextProperty, value); }
}
// public static readonly DependencyProperty AlwaysAllowDefaultProperty =
// DependencyProperty.Register("AlwaysAllowDefault", typeof(bool), typeof(FormattingOption),
// new FrameworkPropertyMetadata());
//
// public bool AlwaysAllowDefault {
// get { return (bool)GetValue(AlwaysAllowDefaultProperty); }
// set { SetValue(AlwaysAllowDefaultProperty, value); }
// }
public string Option
{
get;
set;
}
public bool AlwaysAllowDefault
{
get;
set;
}
}
/// <summary>
@ -133,6 +140,15 @@ namespace CSharpBinding.OptionPanels @@ -133,6 +140,15 @@ namespace CSharpBinding.OptionPanels
set { SetValue(AllowPresetsProperty, value); }
}
public static readonly DependencyProperty OverrideGlobalIndentationProperty =
DependencyProperty.Register("OverrideGlobalIndentation", typeof(bool), typeof(CSharpFormattingEditor),
new FrameworkPropertyMetadata());
public bool OverrideGlobalIndentation {
get { return (bool)GetValue(OverrideGlobalIndentationProperty); }
set { SetValue(OverrideGlobalIndentationProperty, value); }
}
static void OnOptionsContainerPropertyChanged(DependencyObject o, DependencyPropertyChangedEventArgs e)
{
var editor = o as CSharpFormattingEditor;
@ -197,7 +213,7 @@ namespace CSharpBinding.OptionPanels @@ -197,7 +213,7 @@ namespace CSharpBinding.OptionPanels
}
}
public ObservableCollection<IFormattingItemContainer> RootChildren
public ObservableCollection<DependencyObject> RootChildren
{
get {
// rootEntries object is only the root container, its children should be shown directly

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/OptionPanels/CSharpFormattingOptionPanel.xaml

@ -19,7 +19,7 @@ @@ -19,7 +19,7 @@
<CheckBox
Name="autoFormattingCheckBox"
Content="{core:Localize CSharpBinding.Formatting.AutoFormat}"
IsChecked="{sd:OptionBinding fstrategy:CSharpFormattingOptionsPersistence.AutoFormatting}"
IsChecked="{sd:OptionBinding fstrategy:CSharpFormattingPolicies.AutoFormatting}"
Margin="0,0,0,10" />
<local:CSharpFormattingEditor x:Name="formattingEditor" Grid.Row="1" Margin="0,0,0,0" />
</Grid>

15
src/AddIns/BackendBindings/CSharpBinding/Project/Src/OptionPanels/CSharpFormattingOptionPanel.xaml.cs

@ -40,7 +40,7 @@ namespace CSharpBinding.OptionPanels @@ -40,7 +40,7 @@ namespace CSharpBinding.OptionPanels
internal class CSharpGlobalFormattingOptionPanel : CSharpFormattingOptionPanel
{
public CSharpGlobalFormattingOptionPanel()
: base(CSharpFormattingOptionsPersistence.GlobalOptions, true)
: base(CSharpFormattingPolicies.Instance.GlobalOptions, true, false)
{
autoFormattingCheckBox.Visibility = Visibility.Visible;
}
@ -52,7 +52,7 @@ namespace CSharpBinding.OptionPanels @@ -52,7 +52,7 @@ namespace CSharpBinding.OptionPanels
internal class CSharpSolutionFormattingOptionPanel : CSharpFormattingOptionPanel
{
public CSharpSolutionFormattingOptionPanel()
: base(CSharpFormattingOptionsPersistence.SolutionOptions, true)
: base(CSharpFormattingPolicies.Instance.SolutionOptions, true, true)
{
autoFormattingCheckBox.Visibility = Visibility.Collapsed;
}
@ -63,25 +63,26 @@ namespace CSharpBinding.OptionPanels @@ -63,25 +63,26 @@ namespace CSharpBinding.OptionPanels
/// </summary>
internal partial class CSharpFormattingOptionPanel : OptionPanel
{
readonly CSharpFormattingOptionsPersistence persistenceHelper;
readonly CSharpFormattingPolicy formattingPolicy;
bool isDirty;
public CSharpFormattingOptionPanel(CSharpFormattingOptionsPersistence persistenceHelper, bool allowPresets)
public CSharpFormattingOptionPanel(CSharpFormattingPolicy persistenceHelper, bool allowPresets, bool overrideGlobalIndentation)
{
if (persistenceHelper == null)
throw new ArgumentNullException("persistenceHelper");
this.persistenceHelper = persistenceHelper;
this.formattingPolicy = persistenceHelper;
this.isDirty = false;
InitializeComponent();
formattingEditor.AllowPresets = allowPresets;
formattingEditor.OverrideGlobalIndentation = overrideGlobalIndentation;
}
public override void LoadOptions()
{
base.LoadOptions();
formattingEditor.OptionsContainer = persistenceHelper.StartEditing();
formattingEditor.OptionsContainer = formattingPolicy.StartEditing();
formattingEditor.OptionsContainer.PropertyChanged += ContainerPropertyChanged;
}
@ -94,7 +95,7 @@ namespace CSharpBinding.OptionPanels @@ -94,7 +95,7 @@ namespace CSharpBinding.OptionPanels
{
// Only save container, if some option really has changed
formattingEditor.OptionsContainer.PropertyChanged -= ContainerPropertyChanged;
return (!isDirty || persistenceHelper.Save()) && base.SaveOptions();
return (!isDirty || formattingPolicy.Save()) && base.SaveOptions();
}
}
}

15
src/AddIns/BackendBindings/CSharpBinding/Project/Src/OptionPanels/CSharpProjectFormattingOptions.xaml.cs

@ -35,7 +35,7 @@ namespace CSharpBinding.OptionPanels @@ -35,7 +35,7 @@ namespace CSharpBinding.OptionPanels
/// </summary>
internal partial class CSharpProjectFormattingOptionPanel : ProjectOptionPanel
{
CSharpFormattingOptionsPersistence persistenceHelper;
CSharpFormattingPolicy formattingPolicy;
public CSharpProjectFormattingOptionPanel()
{
@ -45,18 +45,19 @@ namespace CSharpBinding.OptionPanels @@ -45,18 +45,19 @@ namespace CSharpBinding.OptionPanels
protected override void Load(ICSharpCode.SharpDevelop.Project.MSBuildBasedProject project, string configuration, string platform)
{
base.Load(project, configuration, platform);
if (persistenceHelper != null) {
persistenceHelper.OptionsContainer.PropertyChanged -= ContainerPropertyChanged;
if (formattingPolicy != null) {
formattingPolicy.OptionsContainer.PropertyChanged -= ContainerPropertyChanged;
}
persistenceHelper = CSharpFormattingOptionsPersistence.GetProjectOptions(project);
formattingEditor.OptionsContainer = persistenceHelper.OptionsContainer;
formattingPolicy = CSharpFormattingPolicies.Instance.GetProjectOptions(project);
formattingEditor.OptionsContainer = formattingPolicy.OptionsContainer;
formattingEditor.AllowPresets = true;
persistenceHelper.OptionsContainer.PropertyChanged += ContainerPropertyChanged;
formattingEditor.OverrideGlobalIndentation = true;
formattingPolicy.OptionsContainer.PropertyChanged += ContainerPropertyChanged;
}
protected override bool Save(ICSharpCode.SharpDevelop.Project.MSBuildBasedProject project, string configuration, string platform)
{
bool success = (persistenceHelper != null) && persistenceHelper.Save();
bool success = (formattingPolicy != null) && formattingPolicy.Save();
return base.Save(project, configuration, platform) && success;
}

150
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Parser/CSharpSymbolSearch.cs

@ -24,6 +24,7 @@ using System.Runtime.InteropServices; @@ -24,6 +24,7 @@ using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.NRefactory.Analysis;
using CSharpBinding.Parser;
using ICSharpCode.AvalonEdit.Document;
using ICSharpCode.AvalonEdit.Highlighting;
@ -51,27 +52,46 @@ namespace CSharpBinding @@ -51,27 +52,46 @@ namespace CSharpBinding
/// </summary>
public class CSharpSymbolSearch : ISymbolSearch
{
IProject project;
ICompilation compilation;
FindReferences fr = new FindReferences();
IList<IFindReferenceSearchScope> searchScopes;
IList<string>[] interestingFileNames;
int workAmount;
double workAmountInverse;
readonly IProject project;
readonly ICompilation compilation;
readonly FindReferences fr = new FindReferences();
readonly IList<IFindReferenceSearchScope> searchScopes;
readonly Dictionary<string, IList<IFindReferenceSearchScope>> searchScopesPerFile;
readonly int workAmount;
readonly double workAmountInverse;
public CSharpSymbolSearch(IProject project, ISymbol entity)
{
this.project = project;
searchScopes = fr.GetSearchScopes(entity);
compilation = SD.ParserService.GetCompilation(project);
interestingFileNames = new IList<string>[searchScopes.Count];
var relatedSymbols = GetRelatedSymbols(entity);
if ((relatedSymbols != null) && relatedSymbols.Any()) {
searchScopes = relatedSymbols.SelectMany(e => fr.GetSearchScopes(e)).ToList();
} else {
searchScopes = fr.GetSearchScopes(entity);
}
searchScopesPerFile = new Dictionary<string, IList<IFindReferenceSearchScope>>();
for (int i = 0; i < searchScopes.Count; i++) {
interestingFileNames[i] = fr.GetInterestingFiles(searchScopes[i], compilation).Select(f => f.FileName).ToList();
workAmount += interestingFileNames[i].Count;
var thisSearchScope = searchScopes[i];
var interestingFiles = fr.GetInterestingFiles(thisSearchScope, compilation).Select(f => f.FileName);
foreach (var file in interestingFiles) {
if (!searchScopesPerFile.ContainsKey(file))
searchScopesPerFile[file] = new List<IFindReferenceSearchScope>();
searchScopesPerFile[file].Add(thisSearchScope);
workAmount++;
}
}
workAmountInverse = 1.0 / workAmount;
}
IEnumerable<ISymbol> GetRelatedSymbols(ISymbol entity)
{
TypeGraph typeGraph = new TypeGraph(new [] { compilation.MainAssembly });
var symbolCollector = new SymbolCollector();
return symbolCollector.GetRelatedSymbols(typeGraph, entity);
}
public double WorkAmount {
get { return workAmount; }
}
@ -83,38 +103,36 @@ namespace CSharpBinding @@ -83,38 +103,36 @@ namespace CSharpBinding
var cancellationToken = args.ProgressMonitor.CancellationToken;
return Task.Run(
() => {
for (int i = 0; i < searchScopes.Count; i++) {
IFindReferenceSearchScope searchScope = searchScopes[i];
object progressLock = new object();
Parallel.ForEach(
interestingFileNames[i],
new ParallelOptions {
MaxDegreeOfParallelism = Environment.ProcessorCount,
CancellationToken = cancellationToken
},
delegate (string fileName) {
try {
FindReferencesInFile(args, searchScope, FileName.Create(fileName), callback, cancellationToken);
} catch (OperationCanceledException) {
throw;
} catch (Exception ex) {
throw new ApplicationException("Error searching in file '" + fileName + "'", ex);
}
lock (progressLock)
args.ProgressMonitor.Progress += workAmountInverse;
});
}
object progressLock = new object();
Parallel.ForEach(
searchScopesPerFile.Keys,
new ParallelOptions {
MaxDegreeOfParallelism = Environment.ProcessorCount,
CancellationToken = cancellationToken
},
delegate (string fileName) {
try {
FindReferencesInFile(args, searchScopesPerFile[fileName], FileName.Create(fileName), callback, cancellationToken);
} catch (OperationCanceledException) {
throw;
} catch (Exception ex) {
throw new ApplicationException("Error searching in file '" + fileName + "'", ex);
}
lock (progressLock)
args.ProgressMonitor.Progress += workAmountInverse;
});
}, cancellationToken
);
}
void FindReferencesInFile(SymbolSearchArgs args, IFindReferenceSearchScope searchScope, FileName fileName, Action<SearchedFile> callback, CancellationToken cancellationToken)
void FindReferencesInFile(SymbolSearchArgs args, IList<IFindReferenceSearchScope> searchScopeList, FileName fileName, Action<SearchedFile> callback, CancellationToken cancellationToken)
{
ITextSource textSource = args.ParseableFileContentFinder.Create(fileName);
if (textSource == null)
return;
if (searchScope.SearchTerm != null) {
if (textSource.IndexOf(searchScope.SearchTerm, 0, textSource.TextLength, StringComparison.Ordinal) < 0)
if (searchScopeList != null) {
if (!searchScopeList.DistinctBy(scope => scope.SearchTerm ?? String.Empty).Any(
scope => (scope.SearchTerm == null) || (textSource.IndexOf(scope.SearchTerm, 0, textSource.TextLength, StringComparison.Ordinal) >= 0)))
return;
}
@ -134,7 +152,7 @@ namespace CSharpBinding @@ -134,7 +152,7 @@ namespace CSharpBinding
}
fr.FindReferencesInFile(
searchScope, unresolvedFile, parseInfo.SyntaxTree, compilation,
searchScopeList, unresolvedFile, parseInfo.SyntaxTree, compilation,
delegate (AstNode node, ResolveResult result) {
if (document == null) {
document = new ReadOnlyDocument(textSource, fileName);
@ -154,8 +172,18 @@ namespace CSharpBinding @@ -154,8 +172,18 @@ namespace CSharpBinding
if (highlighter != null) {
highlighter.Dispose();
}
if (results.Count > 0)
callback(new SearchedFile(fileName, results));
if (results.Count > 0) {
// Remove overlapping results
List<SearchResultMatch> fixedResults = new List<SearchResultMatch>();
int lastEndOffset = 0;
foreach (var result in results.OrderBy(m => m.StartOffset)) {
if (result.StartOffset >= lastEndOffset) {
fixedResults.Add(result);
lastEndOffset = result.EndOffset;
}
}
callback(new SearchedFile(fileName, fixedResults));
}
}
public Task RenameAsync(SymbolRenameArgs args, Action<PatchedFile> callback, Action<Error> errorCallback)
@ -166,32 +194,30 @@ namespace CSharpBinding @@ -166,32 +194,30 @@ namespace CSharpBinding
return Task.Run(
() => {
bool isNameValid = Mono.CSharp.Tokenizer.IsValidIdentifier(args.NewName);
for (int i = 0; i < searchScopes.Count; i++) {
IFindReferenceSearchScope searchScope = searchScopes[i];
object progressLock = new object();
Parallel.ForEach(
interestingFileNames[i],
new ParallelOptions {
MaxDegreeOfParallelism = Environment.ProcessorCount,
CancellationToken = cancellationToken
},
delegate (string fileName) {
RenameReferencesInFile(args, searchScope, FileName.Create(fileName), callback, errorCallback, isNameValid, cancellationToken);
lock (progressLock)
args.ProgressMonitor.Progress += workAmountInverse;
});
}
object progressLock = new object();
Parallel.ForEach(
searchScopesPerFile.Keys,
new ParallelOptions {
MaxDegreeOfParallelism = Environment.ProcessorCount,
CancellationToken = cancellationToken
},
delegate (string fileName) {
RenameReferencesInFile(args, searchScopesPerFile[fileName], FileName.Create(fileName), callback, errorCallback, isNameValid, cancellationToken);
lock (progressLock)
args.ProgressMonitor.Progress += workAmountInverse;
});
}, cancellationToken
);
}
void RenameReferencesInFile(SymbolRenameArgs args, IFindReferenceSearchScope searchScope, FileName fileName, Action<PatchedFile> callback, Action<Error> errorCallback, bool isNameValid, CancellationToken cancellationToken)
void RenameReferencesInFile(SymbolRenameArgs args, IList<IFindReferenceSearchScope> searchScopeList, FileName fileName, Action<PatchedFile> callback, Action<Error> errorCallback, bool isNameValid, CancellationToken cancellationToken)
{
ITextSource textSource = args.ParseableFileContentFinder.Create(fileName);
if (textSource == null)
return;
if (searchScope.SearchTerm != null) {
if (textSource.IndexOf(searchScope.SearchTerm, 0, textSource.TextLength, StringComparison.Ordinal) < 0)
if (searchScopeList != null) {
if (!searchScopeList.DistinctBy(scope => scope.SearchTerm ?? String.Empty).Any(
scope => (scope.SearchTerm == null) || (textSource.IndexOf(scope.SearchTerm, 0, textSource.TextLength, StringComparison.Ordinal) >= 0)))
return;
}
@ -213,7 +239,7 @@ namespace CSharpBinding @@ -213,7 +239,7 @@ namespace CSharpBinding
CSharpAstResolver resolver = new CSharpAstResolver(compilation, parseInfo.SyntaxTree, unresolvedFile);
fr.RenameReferencesInFile(
new[] { searchScope }, args.NewName, resolver,
searchScopeList, args.NewName, resolver,
delegate (RenameCallbackArguments callbackArgs) {
var node = callbackArgs.NodeToReplace;
string newCode = callbackArgs.NewNode.ToString();
@ -249,10 +275,16 @@ namespace CSharpBinding @@ -249,10 +275,16 @@ namespace CSharpBinding
}
IDocument changedDocument = new TextDocument(document);
var oldVersion = changedDocument.Version;
List<SearchResultMatch> fixedResults = new List<SearchResultMatch>();
int lastStartOffset = changedDocument.TextLength + 1;
foreach (var result in results.OrderByDescending(m => m.StartOffset)) {
changedDocument.Replace(result.StartOffset, result.Length, result.NewCode);
if (result.EndOffset <= lastStartOffset) {
changedDocument.Replace(result.StartOffset, result.Length, result.NewCode);
fixedResults.Add(result);
lastStartOffset = result.StartOffset;
}
}
callback(new PatchedFile(fileName, results, oldVersion, changedDocument.Version));
callback(new PatchedFile(fileName, fixedResults, oldVersion, changedDocument.Version));
}
}
}

7
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Refactoring/CSharpCodeGenerator.cs

@ -86,7 +86,10 @@ namespace CSharpBinding.Refactoring @@ -86,7 +86,10 @@ namespace CSharpBinding.Refactoring
var node = context.RootNode.GetNodeAt<EntityDeclaration>(last.Region.Begin);
var resolver = context.GetResolverStateAfter(node);
var builder = new TypeSystemAstBuilder(resolver);
var delegateDecl = builder.ConvertEntity(eventDefinition.ReturnType.GetDefinition()) as DelegateDeclaration;
var invokeMethod = eventDefinition.ReturnType.GetDelegateInvokeMethod();
if (invokeMethod == null) return;
var importedMethod = resolver.Compilation.Import(invokeMethod);
var delegateDecl = builder.ConvertEntity(importedMethod) as MethodDeclaration;
if (delegateDecl == null) return;
var throwStmt = new ThrowStatement(new ObjectCreateExpression(context.CreateShortType("System", "NotImplementedException")));
var decl = new MethodDeclaration() {
@ -96,7 +99,7 @@ namespace CSharpBinding.Refactoring @@ -96,7 +99,7 @@ namespace CSharpBinding.Refactoring
throwStmt
}
};
var param = delegateDecl.Parameters.Select(p => p.Clone()).OfType<ParameterDeclaration>().ToArray();
var param = delegateDecl.Parameters.Select(p => p.Clone()).ToArray();
decl.Parameters.AddRange(param);
using (Script script = context.StartScript()) {

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Refactoring/InsertCtorDialog.xaml.cs

@ -171,7 +171,7 @@ namespace CSharpBinding.Refactoring @@ -171,7 +171,7 @@ namespace CSharpBinding.Refactoring
using (StringWriter textWriter = new StringWriter(pList)) {
// Output parameter list as string
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(refactoringContext.Compilation.GetProject());
var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(refactoringContext.Compilation.GetProject());
CSharpOutputVisitor outputVisitor = new CSharpOutputVisitor(textWriter, formattingOptions.OptionsContainer.GetEffectiveOptions());
for (int i = 0; i < parameters.Count; i++) {
if (i > 0)

2
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Refactoring/MoveTypeToFileContextAction.cs

@ -109,7 +109,7 @@ namespace CSharpBinding.Refactoring @@ -109,7 +109,7 @@ namespace CSharpBinding.Refactoring
|| ch is UsingAliasDeclaration
|| ch is ExternAliasDeclaration);
StringBuilder newCode = new StringBuilder(header);
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(compilation.GetProject());
var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(compilation.GetProject());
CSharpOutputVisitor visitor = new CSharpOutputVisitor(new StringWriter(newCode), formattingOptions.OptionsContainer.GetEffectiveOptions());
foreach (var topLevelUsing in topLevelUsings)

9
src/AddIns/BackendBindings/CSharpBinding/Project/Src/Refactoring/SDRefactoringContext.cs

@ -119,13 +119,16 @@ namespace CSharpBinding.Refactoring @@ -119,13 +119,16 @@ namespace CSharpBinding.Refactoring
public Script StartScript()
{
var formattingOptions = CSharpFormattingOptionsPersistence.GetProjectOptions(resolver.Compilation.GetProject());
var formattingOptions = CSharpFormattingPolicies.Instance.GetProjectOptions(resolver.Compilation.GetProject());
if (editor != null)
return new EditorScript(editor, this, formattingOptions.OptionsContainer.GetEffectiveOptions());
else if (document == null || document is ReadOnlyDocument)
throw new InvalidOperationException("Cannot start a script in a read-only context");
else
return new DocumentScript(document, formattingOptions.OptionsContainer.GetEffectiveOptions(), this.TextEditorOptions);
else {
var textEditorOptions = this.TextEditorOptions;
formattingOptions.OptionsContainer.CustomizeEditorOptions(textEditorOptions);
return new DocumentScript(document, formattingOptions.OptionsContainer.GetEffectiveOptions(), textEditorOptions);
}
}
public IDocument Document {

6
src/AddIns/Debugger/Debugger.AddIn/Service/DebuggeeExceptionForm.cs

@ -104,9 +104,11 @@ namespace ICSharpCode.SharpDevelop.Services @@ -104,9 +104,11 @@ namespace ICSharpCode.SharpDevelop.Services
return;
int start = index;
// find start of current line
while (--start > 0 && fullText[start - 1] != '\n');
while (start > 0 && fullText[start - 1] != '\n')
start--;
// find end of current line
while (++index < fullText.Length && fullText[index] != '\n');
while (index < fullText.Length && fullText[index] != '\n')
index++;
string textLine = fullText.Substring(start, index - start);

3
src/AddIns/Debugger/Debugger.Core/NDebugger.cs

@ -19,6 +19,7 @@ @@ -19,6 +19,7 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using Debugger.Interop;
@ -265,7 +266,7 @@ namespace Debugger @@ -265,7 +266,7 @@ namespace Debugger
public void Detach()
{
// Detach all processes.
foreach(Process process in this.Processes) {
foreach(Process process in this.Processes.ToArray()) {
if (process == null || process.HasExited)
continue;
process.Detach();

12
src/AddIns/Debugger/Debugger.Core/Process.cs

@ -527,8 +527,16 @@ namespace Debugger @@ -527,8 +527,16 @@ namespace Debugger
System.Threading.Thread.Sleep(0);
// Stop&terminate - both must be called
corProcess.Stop(uint.MaxValue);
corProcess.Terminate(0);
try {
corProcess.Stop(uint.MaxValue);
corProcess.Terminate(0);
} catch (COMException ex) {
if (ex.ErrorCode == unchecked((int)0x80131301)) {
// COMException (0x80131301): Process was terminated.
} else {
throw;
}
}
this.TerminateCommandIssued = true;
// Do not mark the process as exited

18
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/CodeEditorAdapter.cs

@ -38,12 +38,14 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -38,12 +38,14 @@ namespace ICSharpCode.AvalonEdit.AddIn
sealed class CodeEditorAdapter : CodeCompletionEditorAdapter
{
readonly CodeEditor codeEditor;
ITextEditorOptions options;
public CodeEditorAdapter(CodeEditor codeEditor, CodeEditorView textEditor) : base(textEditor)
{
if (codeEditor == null)
throw new ArgumentNullException("codeEditor");
this.codeEditor = codeEditor;
options = CodeEditorOptions.Instance;
}
public override FileName FileName {
@ -78,9 +80,14 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -78,9 +80,14 @@ namespace ICSharpCode.AvalonEdit.AddIn
internal void DetachExtensions()
{
if (extensions != null) {
foreach (var extension in extensions)
extension.Detach();
// Detach extensions in reverse order
for (int i = extensions.Count - 1; i >= 0; i--) {
extensions[i].Detach();
}
}
// Switch to global options, if no specific options service is registered
options = this.GetService<ITextEditorOptions>() ?? CodeEditorOptions.Instance;
}
@ -90,6 +97,13 @@ namespace ICSharpCode.AvalonEdit.AddIn @@ -90,6 +97,13 @@ namespace ICSharpCode.AvalonEdit.AddIn
foreach (var extension in extensions)
extension.Attach(this);
}
// If we have any registered ITextEditorOptions service now, use it, otherwise global options
options = this.GetService<ITextEditorOptions>() ?? CodeEditorOptions.Instance;
}
public override ITextEditorOptions Options {
get { return options; }
}
sealed class OptionControlledIndentationStrategy : IndentationStrategyAdapter

1
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/ContextActions/GoToEntityAction.cs

@ -23,6 +23,7 @@ using System.Threading.Tasks; @@ -23,6 +23,7 @@ using System.Threading.Tasks;
using ICSharpCode.AvalonEdit.CodeCompletion;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.Editor.CodeCompletion;
using ICSharpCode.SharpDevelop.Editor.ContextActions;
using ICSharpCode.SharpDevelop.Refactoring;

1
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/QuickClassBrowser.cs

@ -26,6 +26,7 @@ using ICSharpCode.NRefactory; @@ -26,6 +26,7 @@ using ICSharpCode.NRefactory;
using ICSharpCode.NRefactory.TypeSystem;
using ICSharpCode.NRefactory.TypeSystem.Implementation;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.Editor.CodeCompletion;
using ICSharpCode.SharpDevelop.Parser;
using ICSharpCode.SharpDevelop.Project;

11
src/AddIns/DisplayBindings/AvalonEdit.AddIn/Src/XmlDoc/XmlDocTooltipProvider.cs

@ -80,6 +80,17 @@ namespace ICSharpCode.AvalonEdit.AddIn.XmlDoc @@ -80,6 +80,17 @@ namespace ICSharpCode.AvalonEdit.AddIn.XmlDoc
base.OnLostKeyboardFocus(e);
this.IsOpen = false;
}
protected override void OnMouseLeave(MouseEventArgs e)
{
base.OnMouseLeave(e);
// When the mouse is over the popup, it is possible for SharpDevelop to be minimized,
// or moved into the background, and yet the popup stays open.
// We don't have a good method here to check whether the mouse moved back into the text area
// or somewhere else, so we'll just close the popup.
if (CloseWhenMouseMovesAway)
this.IsOpen = false;
}
}
object CreateTooltip(IType type)

19
src/AddIns/DisplayBindings/FormsDesigner/Project/Src/FormKeyHandler.cs

@ -135,18 +135,17 @@ namespace ICSharpCode.FormsDesigner @@ -135,18 +135,17 @@ namespace ICSharpCode.FormsDesigner
selectionService.SetSelectedComponents(components);
}
return true;
}
else if(keyPressed == Keys.Escape) {
ISelectionService selectionService = (ISelectionService)formDesigner.Host.GetService(typeof(ISelectionService));
ICollection components = selectionService.GetSelectedComponents();
} else if (keyPressed == Keys.Escape) {
ISelectionService selectionService = (ISelectionService)formDesigner.Host.GetService(typeof(ISelectionService));
ICollection components = selectionService.GetSelectedComponents();
if (components.Count == 1) {
Control ctrl = components.OfType<Control>().FirstOrDefault();
if (ctrl != null && ctrl.Parent != null) {
selectionService.SetSelectedComponents(new IComponent[] { ctrl.Parent }, SelectionTypes.Primary);
}
Control ctrl = components.OfType<Control>().FirstOrDefault();
if (ctrl != null && ctrl.Parent != null) {
selectionService.SetSelectedComponents(new IComponent[] { ctrl.Parent }, SelectionTypes.Primary);
}
}
return true;
}
return true;
}
return false;
}

8
src/AddIns/DisplayBindings/HexEditor/Project/Src/Editor.cs

@ -1413,6 +1413,14 @@ namespace HexEditor @@ -1413,6 +1413,14 @@ namespace HexEditor
this.Delete();
}
break;
// Ctrl-Y is pressed -> redo
case 89:
Redo();
break;
// Ctrl-Z is pressed -> undo
case 90:
Undo();
break;
}
break;
}

28
src/AddIns/DisplayBindings/ILSpyAddIn/ILSpyParser.cs

@ -20,6 +20,7 @@ using System; @@ -20,6 +20,7 @@ using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using ICSharpCode.Core;
using ICSharpCode.NRefactory;
@ -82,7 +83,32 @@ namespace ICSharpCode.ILSpyAddIn @@ -82,7 +83,32 @@ namespace ICSharpCode.ILSpyAddIn
public ResolveResult ResolveSnippet(ParseInformation parseInfo, TextLocation location, string codeSnippet, ICompilation compilation, CancellationToken cancellationToken)
{
return null;
var decompiledParseInfo = parseInfo as ILSpyFullParseInformation;
if (decompiledParseInfo == null)
throw new ArgumentException("ParseInfo does not have SyntaxTree");
CSharpAstResolver contextResolver = new CSharpAstResolver(compilation, decompiledParseInfo.SyntaxTree, null);
var node = decompiledParseInfo.SyntaxTree.GetNodeAt(location);
CSharpResolver context;
if (node != null)
context = contextResolver.GetResolverStateAfter(node, cancellationToken);
else
context = new CSharpResolver(compilation);
CSharpParser parser = new CSharpParser();
var expr = parser.ParseExpression(codeSnippet);
if (parser.HasErrors)
return new ErrorResolveResult(SpecialType.UnknownType, PrintErrorsAsString(parser.Errors), TextLocation.Empty);
CSharpAstResolver snippetResolver = new CSharpAstResolver(context, expr);
return snippetResolver.Resolve(expr, cancellationToken);
}
string PrintErrorsAsString(IEnumerable<Error> errors)
{
StringBuilder builder = new StringBuilder();
foreach (var error in errors)
builder.AppendLine(error.Message);
return builder.ToString();
}
public void FindLocalReferences(ParseInformation parseInfo, ITextSource fileContent, IVariable variable, ICompilation compilation, Action<SearchResultMatch> callback, CancellationToken cancellationToken)

1
src/AddIns/DisplayBindings/IconEditor/PickFormatDialog.Designer.cs generated

@ -133,7 +133,6 @@ namespace ICSharpCode.IconEditor @@ -133,7 +133,6 @@ namespace ICSharpCode.IconEditor
"Monochrome",
"4 bit",
"8 bit",
"16 bit",
"24 bit",
"32 bit"});
this.colorDepthComboBox.Location = new System.Drawing.Point(93, 73);

52
src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Project/DesignPanel.cs

@ -368,8 +368,7 @@ namespace ICSharpCode.WpfDesign.Designer @@ -368,8 +368,7 @@ namespace ICSharpCode.WpfDesign.Designer
void DesignPanel_KeyDown(object sender, KeyEventArgs e)
{
if (e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Down)
{
if (e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Down) {
e.Handled = true;
if (placementOp == null) {
@ -378,33 +377,46 @@ namespace ICSharpCode.WpfDesign.Designer @@ -378,33 +377,46 @@ namespace ICSharpCode.WpfDesign.Designer
placementOp = PlacementOperation.Start(Context.Services.Selection.SelectedItems, PlacementType.Move);
}
switch (e.Key) {
case Key.Left:
dx += Keyboard.IsKeyDown(Key.LeftShift) ? -10 : -1;
break;
case Key.Up:
dy += Keyboard.IsKeyDown(Key.LeftShift) ? -10 : -1;
break;
case Key.Right:
dx += Keyboard.IsKeyDown(Key.LeftShift) ? 10 : 1;
break;
case Key.Down:
dy += Keyboard.IsKeyDown(Key.LeftShift) ? 10 : 1;
break;
}
dx += (e.Key == Key.Left) ? Keyboard.IsKeyDown(Key.LeftShift) ? -10 : -1 : 0;
dy += (e.Key == Key.Up) ? Keyboard.IsKeyDown(Key.LeftShift) ? -10 : -1 : 0;
dx += (e.Key == Key.Right) ? Keyboard.IsKeyDown(Key.LeftShift) ? 10 : 1 : 0;
dy += (e.Key == Key.Down) ? Keyboard.IsKeyDown(Key.LeftShift) ? 10 : 1 : 0;
foreach (PlacementInformation info in placementOp.PlacedItems)
{
if (!Keyboard.IsKeyDown(Key.LeftCtrl))
{
info.Bounds = new Rect(info.OriginalBounds.Left + dx,
info.OriginalBounds.Top + dy,
info.OriginalBounds.Width,
info.OriginalBounds.Height);
}
else
{
info.Bounds = new Rect(info.OriginalBounds.Left,
info.OriginalBounds.Top,
info.OriginalBounds.Width + dx,
info.OriginalBounds.Height + dy);
}
var bounds = info.OriginalBounds;
if (!Keyboard.IsKeyDown(Key.LeftCtrl)) {
info.Bounds = new Rect(bounds.Left + dx,
bounds.Top + dy,
bounds.Width,
bounds.Height);
} else {
info.Bounds = new Rect(bounds.Left,
bounds.Top,
bounds.Width + dx,
bounds.Height + dy);
}
placementOp.CurrentContainerBehavior.SetPosition(info);
}
}
}
static bool IsPropertySet(UIElement element, DependencyProperty d)
{
return element.ReadLocalValue(d) != DependencyProperty.UnsetValue;
}
protected override void OnQueryCursor(QueryCursorEventArgs e)
{
base.OnQueryCursor(e);

48
src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Project/Extensions/CanvasPlacementSupport.cs

@ -58,6 +58,32 @@ namespace ICSharpCode.WpfDesign.Designer.Extensions @@ -58,6 +58,32 @@ namespace ICSharpCode.WpfDesign.Designer.Extensions
extendedView = (FrameworkElement)this.ExtendedItem.View;
}
public override Rect GetPosition(PlacementOperation operation, DesignItem item)
{
UIElement child = item.View;
if (child == null)
return Rect.Empty;
double x, y;
if (IsPropertySet(child, Canvas.LeftProperty) || !IsPropertySet(child, Canvas.RightProperty)) {
x = GetCanvasProperty(child, Canvas.LeftProperty);
} else {
x = extendedComponent.ActualWidth - GetCanvasProperty(child, Canvas.RightProperty) - child.RenderSize.Width;
}
if (IsPropertySet(child, Canvas.TopProperty) || !IsPropertySet(child, Canvas.BottomProperty)) {
y = GetCanvasProperty(child, Canvas.TopProperty);
} else {
y = extendedComponent.ActualHeight - GetCanvasProperty(child, Canvas.BottomProperty) - child.RenderSize.Height;
}
var p = new Point(x, y);
return new Rect(p, child.RenderSize);
}
public override void SetPosition(PlacementInformation info)
{
base.SetPosition(info);
@ -66,28 +92,26 @@ namespace ICSharpCode.WpfDesign.Designer.Extensions @@ -66,28 +92,26 @@ namespace ICSharpCode.WpfDesign.Designer.Extensions
UIElement child = info.Item.View;
Rect newPosition = info.Bounds;
if (IsPropertySet(child, Canvas.RightProperty))
{
if (IsPropertySet(child, Canvas.LeftProperty) || !IsPropertySet(child, Canvas.RightProperty)) {
if (newPosition.Left != GetCanvasProperty(child, Canvas.LeftProperty)) {
info.Item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(newPosition.Left);
}
} else {
var newR = extendedComponent.ActualWidth - newPosition.Right;
if (newR != GetCanvasProperty(child, Canvas.RightProperty))
info.Item.Properties.GetAttachedProperty(Canvas.RightProperty).SetValue(newR);
}
else if (newPosition.Left != GetCanvasProperty(child, Canvas.LeftProperty))
{
info.Item.Properties.GetAttachedProperty(Canvas.LeftProperty).SetValue(newPosition.Left);
}
if (IsPropertySet(child, Canvas.BottomProperty))
{
if (IsPropertySet(child, Canvas.TopProperty) || !IsPropertySet(child, Canvas.BottomProperty)) {
if (newPosition.Top != GetCanvasProperty(child, Canvas.TopProperty)) {
info.Item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(newPosition.Top);
}
} else {
var newB = extendedComponent.ActualHeight - newPosition.Bottom;
if (newB != GetCanvasProperty(child, Canvas.BottomProperty))
info.Item.Properties.GetAttachedProperty(Canvas.BottomProperty).SetValue(newB);
}
else if (newPosition.Top != GetCanvasProperty(child, Canvas.TopProperty))
{
info.Item.Properties.GetAttachedProperty(Canvas.TopProperty).SetValue(newPosition.Top);
}
if (info.Item == Services.Selection.PrimarySelection)
{

12
src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Project/Extensions/SnaplinePlacementBehavior.cs

@ -116,7 +116,10 @@ namespace ICSharpCode.WpfDesign.Designer.Extensions @@ -116,7 +116,10 @@ namespace ICSharpCode.WpfDesign.Designer.Extensions
if (operation.Type == PlacementType.Resize) {
if (info.ResizeThumbAlignment != null && info.ResizeThumbAlignment.Value.Vertical == VerticalAlignment.Top) {
bounds.Y += delta;
bounds.Y += delta;
bounds.Height = Math.Max(0, bounds.Height - delta);
} else {
bounds.Height = Math.Max(0, bounds.Height + delta);
}
bounds.Height = Math.Max(0, bounds.Height - delta);
info.Bounds = bounds;
@ -137,7 +140,10 @@ namespace ICSharpCode.WpfDesign.Designer.Extensions @@ -137,7 +140,10 @@ namespace ICSharpCode.WpfDesign.Designer.Extensions
if (operation.Type == PlacementType.Resize) {
if (info.ResizeThumbAlignment != null && info.ResizeThumbAlignment.Value.Horizontal == HorizontalAlignment.Left) {
bounds.X += delta;
bounds.X += delta;
bounds.Width = Math.Max(0, bounds.Width - delta);
} else {
bounds.Width = Math.Max(0, bounds.Width + delta);
}
bounds.Width = Math.Max(0, bounds.Width - delta);
info.Bounds = bounds;
@ -183,7 +189,7 @@ namespace ICSharpCode.WpfDesign.Designer.Extensions @@ -183,7 +189,7 @@ namespace ICSharpCode.WpfDesign.Designer.Extensions
yield return designItem;
if (designItem.ContentProperty.Value != null) {
yield return designItem.ContentProperty.Value;
designItem = designItem.ContentProperty.Value;
designItem = ExtendedItem; //set designitem back to current control after yield
}
}
}

12
src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Project/Xaml/XamlModelProperty.cs

@ -121,6 +121,18 @@ namespace ICSharpCode.WpfDesign.Designer.Xaml @@ -121,6 +121,18 @@ namespace ICSharpCode.WpfDesign.Designer.Xaml
}
}
public override string TextValue
{
get {
var xamlTextValue = _property.PropertyValue as XamlTextValue;
if (xamlTextValue != null) {
return xamlTextValue.Text;
}
return null;
}
}
// There may be multiple XamlModelProperty instances for the same property,
// so this class may not have any mutable fields / events - instead,
// we forward all event handlers to the XamlProperty.

115
src/AddIns/DisplayBindings/WpfDesign/WpfDesign.Designer/Tests/Designer/ModelTests.cs

@ -639,6 +639,34 @@ namespace ICSharpCode.WpfDesign.Tests.Designer @@ -639,6 +639,34 @@ namespace ICSharpCode.WpfDesign.Tests.Designer
AddBindingWithStaticResourceWhereResourceOnSameElement(true);
}
[Test]
public void AddStaticResourceWhereResourceOnSameElement()
{
DesignItem button = CreateCanvasContext("<Button/>");
DesignItem canvas = button.Parent;
DesignItemProperty resProp = button.Properties.GetProperty("Resources");
Assert.IsTrue(resProp.IsCollection);
DesignItem exampleClassItem = canvas.Services.Component.RegisterComponentForDesigner(new ExampleClass());
exampleClassItem.Key = "res1";
resProp.CollectionElements.Add(exampleClassItem);
button.Properties["Tag"].SetValue(new StaticResourceExtension());
button.Properties["Tag"].Value.Properties["ResourceKey"].SetValue("res1");
string expectedXaml = "<Button>\n" +
" <Button.Resources>\n" +
" <t:ExampleClass x:Key=\"res1\" />\n" +
" </Button.Resources>\n" +
" <Button.Tag>\n" +
" <StaticResourceExtension ResourceKey=\"res1\" />\n" +
" </Button.Tag>\n" +
"</Button>";
AssertCanvasDesignerOutput(expectedXaml, button.Context);
AssertLog("");
}
[Test]
public void AddBrushAsResource()
{
@ -667,32 +695,92 @@ namespace ICSharpCode.WpfDesign.Tests.Designer @@ -667,32 +695,92 @@ namespace ICSharpCode.WpfDesign.Tests.Designer
AssertLog("");
}
[Test]
public void AddStringAsResource()
public void AddNativeTypeAsResource(object component, string expectedXamlValue)
{
AddTypeAsResource(component, expectedXamlValue, "Controls0:", new string[] { "xmlns:Controls0=\"clr-namespace:System;assembly=mscorlib\""} );
}
public void AddTypeAsResource(object component, string expectedXamlValue, string typePrefix, String[] additionalXmlns)
{
DesignItem textBlock = CreateCanvasContext("<TextBlock/>");
DesignItem canvas = textBlock.Parent;
DesignItemProperty canvasResources = canvas.Properties.GetProperty("Resources");
DesignItem str = canvas.Services.Component.RegisterComponentForDesigner("stringresource 1");
str.Key = "str1";
DesignItem componentItem = canvas.Services.Component.RegisterComponentForDesigner(component);
componentItem.Key = "res1";
Assert.IsTrue(canvasResources.IsCollection);
canvasResources.CollectionElements.Add(str);
canvasResources.CollectionElements.Add(componentItem);
DesignItemProperty prop = textBlock.Properties[TextBlock.TagProperty];
prop.SetValue(new StaticResourceExtension());
prop.Value.Properties["ResourceKey"].SetValue("res1");
textBlock.Properties[TextBlock.TextProperty].SetValue(new StaticResourceExtension());
DesignItemProperty prop = textBlock.Properties[TextBlock.TextProperty];
prop.Value.Properties["ResourceKey"].SetValue("str1");
string typeName = component.GetType().Name;
string expectedXaml = "<Canvas.Resources>\n" +
" <Controls0:String x:Key=\"str1\">stringresource 1</Controls0:String>\n" +
" <" + typePrefix + typeName + " x:Key=\"res1\">" + expectedXamlValue + "</" + typePrefix + typeName + ">\n" +
"</Canvas.Resources>\n" +
"<TextBlock Text=\"{StaticResource ResourceKey=str1}\" />";
"<TextBlock Tag=\"{StaticResource ResourceKey=res1}\" />";
AssertCanvasDesignerOutput(expectedXaml, textBlock.Context, additionalXmlns);
AssertLog("");
}
[Test]
public void TestTextValue()
{
// An invalid path (in this case containing a question mark), or a path to a file that does not exist, will give the same result.
// It will cause the typeconverter to fail and no value can be get from neither ValueOnInstance nor Value from the Image.Source DesignItemProperty.
// TextValue was added to have a way of getting the xaml value.
string sourceTextValue = "file:///C:/Folder/image?.bmp";
AssertCanvasDesignerOutput(expectedXaml, textBlock.Context, "xmlns:Controls0=\"clr-namespace:System;assembly=mscorlib\"");
string xaml = "<Image Source=\"" + sourceTextValue + "\" />";
DesignItem image = CreateCanvasContext(xaml);
var sourceProp = image.Properties[Image.SourceProperty];
Assert.IsNull(sourceProp.ValueOnInstance);
Assert.IsNull(sourceProp.Value);
Assert.IsNotNull(sourceProp.TextValue);
Assert.AreEqual(sourceTextValue, sourceProp.TextValue);
string expectedXaml = xaml;
AssertCanvasDesignerOutput(expectedXaml, image.Context);
AssertLog("");
}
[Test]
public void AddStringAsResource()
{
AddNativeTypeAsResource("stringresource 1", "stringresource 1");
}
[Test]
public void AddDoubleAsResource()
{
AddNativeTypeAsResource(0.0123456789d, "0.0123456789");
}
[Test]
public void AddInt32AsResource()
{
const int i = 123;
AddNativeTypeAsResource(i, "123");
}
[Test]
public void AddWpfEnumAsResource()
{
AddTypeAsResource(VerticalAlignment.Center, "Center", "", new string[0]);
}
[Test]
public void AddCustomEnumAsResource()
{
AddTypeAsResource(MyEnum.One, "One", "t:", new string[0]);
}
}
public class MyMultiConverter : IMultiValueConverter
@ -717,4 +805,9 @@ namespace ICSharpCode.WpfDesign.Tests.Designer @@ -717,4 +805,9 @@ namespace ICSharpCode.WpfDesign.Tests.Designer
set { stringProp = value; }
}
}
public enum MyEnum
{
One, Two
}
}

69
src/AddIns/DisplayBindings/WpfDesign/WpfDesign.XamlDom/Project/MarkupExtensionPrinter.cs

@ -38,36 +38,7 @@ namespace ICSharpCode.WpfDesign.XamlDom @@ -38,36 +38,7 @@ namespace ICSharpCode.WpfDesign.XamlDom
return false;
}
foreach (var property in obj.Properties.Where((prop) => prop.IsSet))
{
var value = property.PropertyValue;
if (value is XamlTextValue)
continue;
else
{
XamlObject xamlObject = value as XamlObject;
if (xamlObject == null || !xamlObject.IsMarkupExtension)
return false;
else {
var staticResource = xamlObject.Instance as System.Windows.StaticResourceExtension;
if (staticResource != null &&
staticResource.ResourceKey != null) {
XamlObject parent = GetNonMarkupExtensionParent(xamlObject);
if (parent != null) {
var parentLocalResource = parent.ServiceProvider.Resolver.FindLocalResource(staticResource.ResourceKey);
// If resource with the specified key is declared locally on the same object as the StaticResource is being used the markup extension
// must be printed as element to find the resource, otherwise it will search from parent-parent and find none or another resource.
if (parentLocalResource != null)
return false;
}
}
}
}
}
return true;
return CanPrint(obj, false, GetNonMarkupExtensionParent(obj));
}
/// <summary>
@ -115,6 +86,28 @@ namespace ICSharpCode.WpfDesign.XamlDom @@ -115,6 +86,28 @@ namespace ICSharpCode.WpfDesign.XamlDom
return sb.ToString();
}
private static bool CanPrint(XamlObject obj, bool isNested, XamlObject nonMarkupExtensionParent)
{
if ((isNested || obj.ParentObject == nonMarkupExtensionParent) && IsStaticResourceThatReferencesLocalResource(obj, nonMarkupExtensionParent)) {
return false;
}
foreach (var property in obj.Properties.Where((prop) => prop.IsSet)) {
var value = property.PropertyValue;
if (value is XamlTextValue)
continue;
else {
var xamlObject = value as XamlObject;
if (xamlObject == null || !xamlObject.IsMarkupExtension)
return false;
else
return CanPrint(xamlObject, true, nonMarkupExtensionParent);
}
}
return true;
}
private static XamlObject GetNonMarkupExtensionParent(XamlObject markupExtensionObject)
{
System.Diagnostics.Debug.Assert(markupExtensionObject.IsMarkupExtension);
@ -125,5 +118,21 @@ namespace ICSharpCode.WpfDesign.XamlDom @@ -125,5 +118,21 @@ namespace ICSharpCode.WpfDesign.XamlDom
}
return obj;
}
private static bool IsStaticResourceThatReferencesLocalResource(XamlObject obj, XamlObject nonMarkupExtensionParent)
{
var staticResource = obj.Instance as System.Windows.StaticResourceExtension;
if (staticResource != null && staticResource.ResourceKey != null && nonMarkupExtensionParent != null) {
var parentLocalResource = nonMarkupExtensionParent.ServiceProvider.Resolver.FindLocalResource(staticResource.ResourceKey);
// If resource with the specified key is declared locally on the same object as the StaticResource is being used the markup extension
// must be printed as element to find the resource, otherwise it will search from parent-parent and find none or another resource.
if (parentLocalResource != null)
return true;
}
return false;
}
}
}

9
src/AddIns/DisplayBindings/WpfDesign/WpfDesign.XamlDom/Project/XamlDocument.cs

@ -193,7 +193,7 @@ namespace ICSharpCode.WpfDesign.XamlDom @@ -193,7 +193,7 @@ namespace ICSharpCode.WpfDesign.XamlDom
XmlElement xml = _xmlDoc.CreateElement(prefix, elementType.Name, ns);
if (hasStringConverter && XamlObject.GetContentPropertyName(elementType) != null) {
if (hasStringConverter && (XamlObject.GetContentPropertyName(elementType) != null || IsNativeType(instance))) {
xml.InnerText = c.ConvertToInvariantString(instance);
} else if (instance is Brush && forProperty != null) { // TODO: this is a hacky fix, because Brush Editor doesn't
// edit Design Items and so we have no XML, only the Brush
@ -214,8 +214,6 @@ namespace ICSharpCode.WpfDesign.XamlDom @@ -214,8 +214,6 @@ namespace ICSharpCode.WpfDesign.XamlDom
}
}
}
} else if (instance is string) {
xml.InnerText = (string)instance;
}
return new XamlObject(this, xml, elementType, instance);
@ -274,5 +272,10 @@ namespace ICSharpCode.WpfDesign.XamlDom @@ -274,5 +272,10 @@ namespace ICSharpCode.WpfDesign.XamlDom
return prefix;
}
bool IsNativeType(object instance)
{
return instance.GetType().Assembly == typeof(String).Assembly || instance.GetType().IsEnum;
}
}
}

6
src/AddIns/DisplayBindings/WpfDesign/WpfDesign/Project/DesignItemProperty.cs

@ -81,6 +81,12 @@ namespace ICSharpCode.WpfDesign @@ -81,6 +81,12 @@ namespace ICSharpCode.WpfDesign
/// </summary>
public abstract DesignItem Value { get; }
/// <summary>
/// Gets the string value of the property. This property returns null if the value is not set,
/// or if the value is set to a non-primitive value (i.e. represented by a <see cref="DesignItem"/>, accessible through <see cref="Value"/> property).
/// </summary>
public abstract string TextValue { get; }
/// <summary>
/// Is raised when the value of the property changes (by calling <see cref="SetValue"/> or <see cref="Reset"/>).
/// </summary>

12
src/AddIns/Misc/FiletypeRegisterer/Project/Src/RegisterFiletypesPanel.Designer.cs generated

@ -38,7 +38,7 @@ namespace ICSharpCode.FiletypeRegisterer @@ -38,7 +38,7 @@ namespace ICSharpCode.FiletypeRegisterer
}
base.Dispose(disposing);
}
/// <summary>
/// This method is required for Windows Forms designer support.
/// Do not change the method contents inside the source code editor. The Forms designer might
@ -53,24 +53,25 @@ namespace ICSharpCode.FiletypeRegisterer @@ -53,24 +53,25 @@ namespace ICSharpCode.FiletypeRegisterer
// captionLabel
//
this.captionLabel.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
| System.Windows.Forms.AnchorStyles.Right)));
this.captionLabel.Location = new System.Drawing.Point(3, 0);
this.captionLabel.Name = "captionLabel";
this.captionLabel.Size = new System.Drawing.Size(328, 23);
this.captionLabel.TabIndex = 0;
this.captionLabel.Text = "${res:ICSharpCode.SharpDevelop.Gui.Dialogs.OptionPanels.RegisterFiletypesPanel.Ca" +
"ptionLabel}";
"ptionLabel}";
//
// fileTypesListBox
//
this.fileTypesListBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
| System.Windows.Forms.AnchorStyles.Left)
| System.Windows.Forms.AnchorStyles.Right)));
this.fileTypesListBox.IntegralHeight = false;
this.fileTypesListBox.Location = new System.Drawing.Point(3, 26);
this.fileTypesListBox.Name = "fileTypesListBox";
this.fileTypesListBox.Size = new System.Drawing.Size(328, 299);
this.fileTypesListBox.TabIndex = 1;
this.fileTypesListBox.MouseClick += new System.Windows.Forms.MouseEventHandler(this.fileTypesListBox_MouseClick);
//
// RegisterFiletypesPanel
//
@ -79,6 +80,7 @@ namespace ICSharpCode.FiletypeRegisterer @@ -79,6 +80,7 @@ namespace ICSharpCode.FiletypeRegisterer
this.Name = "RegisterFiletypesPanel";
this.Size = new System.Drawing.Size(334, 328);
this.ResumeLayout(false);
}
private System.Windows.Forms.CheckedListBox fileTypesListBox;
private System.Windows.Forms.Label captionLabel;

7
src/AddIns/Misc/FiletypeRegisterer/Project/Src/RegisterFiletypesPanel.cs

@ -80,5 +80,12 @@ namespace ICSharpCode.FiletypeRegisterer @@ -80,5 +80,12 @@ namespace ICSharpCode.FiletypeRegisterer
}
return true;
}
void fileTypesListBox_MouseClick(object sender, System.Windows.Forms.MouseEventArgs e)
{
if (fileTypesListBox.IndexFromPoint(e.X, e.Y) == ListBox.NoMatches) {
fileTypesListBox.SelectedIndex = -1;
}
}
}
}

4
src/AddIns/Misc/PackageManagement/Cmdlets/Project/Src/InstallPackageCmdlet.cs

@ -66,7 +66,9 @@ namespace ICSharpCode.PackageManagement.Cmdlets @@ -66,7 +66,9 @@ namespace ICSharpCode.PackageManagement.Cmdlets
{
ThrowErrorIfProjectNotOpen();
using (IConsoleHostFileConflictResolver resolver = CreateFileConflictResolver()) {
InstallPackage();
using (IDisposable logger = ConsoleHost.CreateLogger(this)) {
InstallPackage();
}
}
}

7
src/AddIns/Misc/PackageManagement/Cmdlets/Project/Src/PackageManagementCmdlet.cs

@ -25,7 +25,7 @@ using NuGet; @@ -25,7 +25,7 @@ using NuGet;
namespace ICSharpCode.PackageManagement.Cmdlets
{
public abstract class PackageManagementCmdlet : PSCmdlet, ITerminatingCmdlet, IPackageScriptSession, IPackageScriptRunner
public abstract class PackageManagementCmdlet : PSCmdlet, ITerminatingCmdlet, IPackageScriptSession, IPackageScriptRunner, ICmdletLogger
{
IPackageManagementConsoleHost consoleHost;
ICmdletTerminatingError terminatingError;
@ -114,5 +114,10 @@ namespace ICSharpCode.PackageManagement.Cmdlets @@ -114,5 +114,10 @@ namespace ICSharpCode.PackageManagement.Cmdlets
script.Run(this);
}
}
void ICmdletLogger.WriteLine(string message)
{
Host.UI.WriteLine(message);
}
}
}

4
src/AddIns/Misc/PackageManagement/Cmdlets/Project/Src/UninstallPackageCmdlet.cs

@ -59,7 +59,9 @@ namespace ICSharpCode.PackageManagement.Cmdlets @@ -59,7 +59,9 @@ namespace ICSharpCode.PackageManagement.Cmdlets
protected override void ProcessRecord()
{
ThrowErrorIfProjectNotOpen();
UninstallPackage();
using (IDisposable logger = ConsoleHost.CreateLogger(this)) {
UninstallPackage();
}
}
void UninstallPackage()

4
src/AddIns/Misc/PackageManagement/Cmdlets/Project/Src/UpdatePackageCmdlet.cs

@ -73,7 +73,9 @@ namespace ICSharpCode.PackageManagement.Cmdlets @@ -73,7 +73,9 @@ namespace ICSharpCode.PackageManagement.Cmdlets
{
ThrowErrorIfProjectNotOpen();
using (IConsoleHostFileConflictResolver resolver = CreateFileConflictResolver()) {
RunUpdate();
using (IDisposable logger = ConsoleHost.CreateLogger(this)) {
RunUpdate();
}
}
}

14
src/AddIns/Misc/PackageManagement/Cmdlets/Test/Src/InstallPackageCmdletTests.cs

@ -321,5 +321,19 @@ namespace PackageManagement.Cmdlets.Tests @@ -321,5 +321,19 @@ namespace PackageManagement.Cmdlets.Tests
operationAwareRepository.AssertOperationWasStartedAndDisposed(RepositoryOperationNames.Install, "Test");
}
[Test]
public void ProcessRecord_PackageIdSpecified_ConsoleHostLoggerIsDisposed()
{
CreateCmdletWithoutActiveProject();
AddDefaultProjectToConsoleHost();
AddPackageSourceToConsoleHost();
SetIdParameter("Test");
RunCmdlet();
fakeConsoleHost.AssertLoggerIsDisposed();
Assert.AreEqual(cmdlet, fakeConsoleHost.CmdletLoggerUsedToCreateLogger);
}
}
}

16
src/AddIns/Misc/PackageManagement/Cmdlets/Test/Src/UninstallPackageCmdletTests.cs

@ -237,8 +237,22 @@ namespace PackageManagement.Cmdlets.Tests @@ -237,8 +237,22 @@ namespace PackageManagement.Cmdlets.Tests
RunCmdlet();
IPackageScriptRunner scriptRunner = uninstallPackageAction.PackageScriptRunner;
Assert.AreEqual(cmdlet, scriptRunner);
}
[Test]
public void ProcessRecord_PackageIdSpecified_ConsoleHostLoggerIsDisposed()
{
CreateCmdletWithoutActiveProject();
AddDefaultProjectToConsoleHost();
AddPackageSourceToConsoleHost();
SetIdParameter("Test");
RunCmdlet();
fakeConsoleHost.AssertLoggerIsDisposed();
Assert.AreEqual(cmdlet, fakeConsoleHost.CmdletLoggerUsedToCreateLogger);
}
}
}

14
src/AddIns/Misc/PackageManagement/Cmdlets/Test/Src/UpdatePackageCmdletTests.cs

@ -832,5 +832,19 @@ namespace PackageManagement.Cmdlets.Tests @@ -832,5 +832,19 @@ namespace PackageManagement.Cmdlets.Tests
operationAwareRepository.AssertOperationWasStartedAndDisposed(RepositoryOperationNames.Update, "Test2");
}
[Test]
public void ProcessRecord_PackageIdSpecified_ConsoleHostLoggerIsDisposed()
{
CreateCmdletWithoutActiveProject();
AddDefaultProjectToConsoleHost();
AddPackageSourceToConsoleHost();
SetIdParameter("Test");
RunCmdlet();
fakeConsoleHost.AssertLoggerIsDisposed();
Assert.AreEqual(cmdlet, fakeConsoleHost.CmdletLoggerUsedToCreateLogger);
}
}
}

3
src/AddIns/Misc/PackageManagement/Project/PackageManagement.csproj

@ -58,6 +58,7 @@ @@ -58,6 +58,7 @@
<RequiredTargetFramework>3.5</RequiredTargetFramework>
</Reference>
<Reference Include="System.Drawing" />
<Reference Include="System.Management.Automation, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
<Reference Include="System.Windows.Forms" />
<Reference Include="System.Xaml">
<RequiredTargetFramework>4.0</RequiredTargetFramework>
@ -243,6 +244,7 @@ @@ -243,6 +244,7 @@
<Compile Include="Src\Scripting\ConsoleHostFileConflictResolver.cs" />
<Compile Include="Src\Scripting\FileConflictAction.cs" />
<Compile Include="Src\Scripting\GlobalMSBuildProjectCollection.cs" />
<Compile Include="Src\Scripting\ICmdletLogger.cs" />
<Compile Include="Src\Scripting\IConsoleHostFileConflictResolver.cs" />
<Compile Include="Src\Scripting\IGlobalMSBuildProjectCollection.cs" />
<Compile Include="Src\Scripting\MSBuildProjectImportsMerger.cs" />
@ -250,6 +252,7 @@ @@ -250,6 +252,7 @@
<Compile Include="Src\Scripting\MSBuildProjectPropertiesMerger.cs" />
<Compile Include="Src\Scripting\MSBuildProjectPropertiesMergeResult.cs" />
<Compile Include="Src\Scripting\NullGlobalMSBuildProjectCollection.cs" />
<Compile Include="Src\Scripting\PackageManagementConsoleHostLogger.cs" />
<Compile Include="Src\Scripting\RunAllProjectPackageScriptsAction.cs" />
<Compile Include="Src\ServiceWithWorkbenchOwner.cs" />
<Compile Include="Src\SettingsProvider.cs" />

17
src/AddIns/Misc/PackageManagement/Project/Src/Design/FakeSettings.cs

@ -18,6 +18,8 @@ @@ -18,6 +18,8 @@
using System;
using System.Collections.Generic;
using System.Linq;
using NuGet;
namespace ICSharpCode.PackageManagement.Design
@ -36,6 +38,8 @@ namespace ICSharpCode.PackageManagement.Design @@ -36,6 +38,8 @@ namespace ICSharpCode.PackageManagement.Design
public Dictionary<string, IList<KeyValuePair<string, string>>> Sections
= new Dictionary<string, IList<KeyValuePair<string, string>>>();
public const string ConfigSectionName = "config";
public FakeSettings()
{
Sections.Add(RegisteredPackageSourceSettings.PackageSourcesSectionName, PackageSources);
@ -200,7 +204,11 @@ namespace ICSharpCode.PackageManagement.Design @@ -200,7 +204,11 @@ namespace ICSharpCode.PackageManagement.Design
public string GetValue(string section, string key, bool isPath)
{
throw new NotImplementedException();
if (Sections.ContainsKey(section)) {
var matchedSection = Sections[section];
return matchedSection.FirstOrDefault(item => item.Key == key).Value;
}
return null;
}
public IList<KeyValuePair<string, string>> GetValues(string section, bool isPath)
@ -212,5 +220,12 @@ namespace ICSharpCode.PackageManagement.Design @@ -212,5 +220,12 @@ namespace ICSharpCode.PackageManagement.Design
{
throw new NotImplementedException();
}
public void SetRepositoryPathSetting(string fullPath)
{
var items = new List<KeyValuePair<string, string>> ();
items.Add (new KeyValuePair<string, string>("repositoryPath", fullPath));
Sections.Add(ConfigSectionName, items);
}
}
}

5
src/AddIns/Misc/PackageManagement/Project/Src/PackageManagementOptions.cs

@ -95,5 +95,10 @@ namespace ICSharpCode.PackageManagement @@ -95,5 +95,10 @@ namespace ICSharpCode.PackageManagement
{
properties.SetList(RecentPackagesPropertyName, recentPackages);
}
public string GetCustomPackagesDirectory()
{
return registeredPackageSourceSettings.Settings.GetRepositoryPath();
}
}
}

4
src/AddIns/Misc/PackageManagement/Project/Src/RegisteredPackageSourceSettings.cs

@ -204,5 +204,9 @@ namespace ICSharpCode.PackageManagement @@ -204,5 +204,9 @@ namespace ICSharpCode.PackageManagement
packageSources = null;
}
}
public ISettings Settings {
get { return settings; }
}
}
}

31
src/AddIns/Misc/PackageManagement/Project/Src/RestorePackagesCommand.cs

@ -18,6 +18,9 @@ @@ -18,6 +18,9 @@
using System;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using ICSharpCode.Core;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.Gui;
@ -71,7 +74,33 @@ namespace ICSharpCode.PackageManagement @@ -71,7 +74,33 @@ namespace ICSharpCode.PackageManagement
var runner = new ProcessRunner();
runner.WorkingDirectory = Path.GetDirectoryName(solution.FileName);
runner.RunInOutputPadAsync(outputMessagesView.OutputCategory, commandLine.Command, commandLine.Arguments).FireAndForget();
runner.RunInOutputPadAsync(outputMessagesView.OutputCategory, commandLine.Command, commandLine.Arguments)
.ContinueWith(task => OnNuGetPackageRestoreComplete(task));
}
void OnNuGetPackageRestoreComplete(Task<int> task)
{
if (task.Exception != null) {
LoggingService.Debug(task.Exception.ToString());
outputMessagesView.AppendLine(task.Exception.Message);
} else {
ForceGenerationOfRepositoriesConfigFile();
}
}
/// <summary>
/// Create a Package Manager for each project to force a new repositories.config file
/// to be generated with references to all projects that have NuGet packages.
/// </summary>
void ForceGenerationOfRepositoriesConfigFile()
{
try {
var repository = PackageManagementServices.RegisteredPackageRepositories.CreateAggregateRepository();
var projects = solution.GetProjects(repository).ToList();
} catch (Exception ex) {
LoggingService.Debug(ex.ToString());
outputMessagesView.AppendLine(ex.Message);
}
}
}
}

16
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataManager/Listhandling/IndexList.cs → src/AddIns/Misc/PackageManagement/Project/Src/Scripting/ICmdletLogger.cs

@ -17,17 +17,15 @@ @@ -17,17 +17,15 @@
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.Generic;
using ICSharpCode.Reporting.DataSource.Comparer;
using System.Management.Automation;
namespace ICSharpCode.Reporting.DataManager.Listhandling
namespace ICSharpCode.PackageManagement.Scripting
{
/// <summary>
/// Description of IndexList.
/// </summary>
public class IndexList :List<BaseComparer>
public interface ICmdletLogger
{
public int CurrentPosition {get;set;}
void WriteError(ErrorRecord error);
void WriteLine(string message);
void WriteVerbose(string message);
void WriteWarning(string message);
}
}

1
src/AddIns/Misc/PackageManagement/Project/Src/Scripting/IPackageManagementConsoleHost.cs

@ -42,6 +42,7 @@ namespace ICSharpCode.PackageManagement.Scripting @@ -42,6 +42,7 @@ namespace ICSharpCode.PackageManagement.Scripting
void SetDefaultRunspace();
IConsoleHostFileConflictResolver CreateFileConflictResolver(FileConflictAction fileConflictAction);
IDisposable CreateLogger(ICmdletLogger logger);
IPackageManagementProject GetProject(string packageSource, string projectName);
IPackageManagementProject GetProject(IPackageRepository sourceRepository, string projectName);

5
src/AddIns/Misc/PackageManagement/Project/Src/Scripting/PackageManagementConsoleHost.cs

@ -295,5 +295,10 @@ namespace ICSharpCode.PackageManagement.Scripting @@ -295,5 +295,10 @@ namespace ICSharpCode.PackageManagement.Scripting
{
return new ConsoleHostFileConflictResolver(packageEvents, fileConflictAction);
}
public IDisposable CreateLogger(ICmdletLogger logger)
{
return new PackageManagementConsoleHostLogger(logger, packageEvents);
}
}
}

75
src/AddIns/Misc/PackageManagement/Project/Src/Scripting/PackageManagementConsoleHostLogger.cs

@ -0,0 +1,75 @@ @@ -0,0 +1,75 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Management.Automation;
using NuGet;
namespace ICSharpCode.PackageManagement.Scripting
{
public class PackageManagementConsoleHostLogger : IDisposable
{
ICmdletLogger logger;
IPackageManagementEvents packageEvents;
public PackageManagementConsoleHostLogger(ICmdletLogger logger, IPackageManagementEvents packageEvents)
{
this.logger = logger;
this.packageEvents = packageEvents;
packageEvents.PackageOperationMessageLogged += PackageOperationMessageLogged;
}
void PackageOperationMessageLogged(object sender, PackageOperationMessageLoggedEventArgs e)
{
Log(e.Message.Level, e.Message.ToString());
}
void Log(MessageLevel level, string message)
{
switch (level) {
case MessageLevel.Debug:
logger.WriteVerbose(message);
break;
case MessageLevel.Warning:
logger.WriteWarning(message);
break;
case MessageLevel.Error:
logger.WriteError(CreateErrorRecord(message));
break;
default:
logger.WriteLine(message);
break;
}
}
ErrorRecord CreateErrorRecord(string message)
{
return new ErrorRecord(
new ApplicationException(message),
"PackageManagementError",
ErrorCategory.NotSpecified,
null);
}
public void Dispose()
{
packageEvents.PackageOperationMessageLogged -= PackageOperationMessageLogged;
}
}
}

5
src/AddIns/Misc/PackageManagement/Project/Src/Scripting/PowerShellMissingConsoleHost.cs

@ -100,5 +100,10 @@ namespace ICSharpCode.PackageManagement.Scripting @@ -100,5 +100,10 @@ namespace ICSharpCode.PackageManagement.Scripting
{
return null;
}
public IDisposable CreateLogger(ICmdletLogger logger)
{
return null;
}
}
}

2
src/AddIns/Misc/PackageManagement/Project/Src/SharpDevelopPackageManagerFactory.cs

@ -32,7 +32,7 @@ namespace ICSharpCode.PackageManagement @@ -32,7 +32,7 @@ namespace ICSharpCode.PackageManagement
: this(
new SharpDevelopPackageRepositoryFactory(),
new SharpDevelopProjectSystemFactory(),
new PackageManagementOptions())
PackageManagementServices.Options)
{
}

15
src/AddIns/Misc/PackageManagement/Project/Src/SolutionPackageRepositoryPath.cs

@ -25,12 +25,11 @@ namespace ICSharpCode.PackageManagement @@ -25,12 +25,11 @@ namespace ICSharpCode.PackageManagement
{
public class SolutionPackageRepositoryPath
{
string packagesRelativeDirectory;
ISolution solution;
DefaultPackagePathResolver pathResolver;
public SolutionPackageRepositoryPath(IProject project)
: this(project, new PackageManagementOptions())
: this(project, PackageManagementServices.Options)
{
}
@ -41,14 +40,18 @@ namespace ICSharpCode.PackageManagement @@ -41,14 +40,18 @@ namespace ICSharpCode.PackageManagement
public SolutionPackageRepositoryPath(ISolution solution, PackageManagementOptions options)
{
packagesRelativeDirectory = options.PackagesDirectory;
this.solution = solution;
GetSolutionPackageRepositoryPath();
PackageRepositoryPath = GetSolutionPackageRepositoryPath(options);
}
void GetSolutionPackageRepositoryPath()
string GetSolutionPackageRepositoryPath(PackageManagementOptions options)
{
PackageRepositoryPath = Path.Combine(solution.Directory, packagesRelativeDirectory);
string customPath = options.GetCustomPackagesDirectory ();
if (!String.IsNullOrEmpty (customPath)) {
return customPath;
}
return Path.Combine (solution.Directory, options.PackagesDirectory);
}
public string PackageRepositoryPath { get; private set; }

2
src/AddIns/Misc/PackageManagement/Test/PackageManagement.Tests.csproj

@ -108,6 +108,7 @@ @@ -108,6 +108,7 @@
<Compile Include="Src\Helpers\CodeElementsExtensions.cs" />
<Compile Include="Src\Helpers\ExceptionThrowingPackageActionRunner.cs" />
<Compile Include="Src\Helpers\ExceptionThrowingProcessPackageAction.cs" />
<Compile Include="Src\Helpers\FakeCmdletLogger.cs" />
<Compile Include="Src\Helpers\FakeCodeGenerator.cs" />
<Compile Include="Src\Helpers\FakeOperationAwarePackageRepository.cs" />
<Compile Include="Src\Helpers\FakeSelectProjectsService.cs" />
@ -194,6 +195,7 @@ @@ -194,6 +195,7 @@
<Compile Include="Src\Scripting\ConsoleHostFileConflictResolverTests.cs" />
<Compile Include="Src\Scripting\MSBuildProjectImportsMergerTests.cs" />
<Compile Include="Src\Scripting\MSBuildProjectPropertiesMergerTests.cs" />
<Compile Include="Src\Scripting\PackageManagementConsoleHostLoggerTests.cs" />
<Compile Include="Src\SettingsProviderTests.cs" />
<Compile Include="Src\UpdatedPackagesTests.cs" />
<Compile Include="Src\UpdatePackagesActionTests.cs" />

38
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/Comparer/GroupComparer.cs → src/AddIns/Misc/PackageManagement/Test/Src/Helpers/FakeCmdletLogger.cs

@ -17,23 +17,39 @@ @@ -17,23 +17,39 @@
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.ObjectModel;
using ICSharpCode.Reporting.BaseClasses;
using ICSharpCode.Reporting.DataManager.Listhandling;
using System.Management.Automation;
using ICSharpCode.PackageManagement.Scripting;
namespace ICSharpCode.Reporting.DataSource.Comparer
namespace PackageManagement.Tests.Helpers
{
/// <summary>
/// Description of GroupComparer.
/// </summary>
public class GroupComparer :SortComparer
public class FakeCmdletLogger : ICmdletLogger
{
public ErrorRecord ErrorRecordLogged;
public GroupComparer (Collection<AbstractColumn> owner, int listIndex, object[] values):base(owner,listIndex,values)
public void WriteError(ErrorRecord error)
{
IndexList = new IndexList();
ErrorRecordLogged = error;
}
public IndexList IndexList {get;private set;}
public string LineLogged;
public void WriteLine(string message)
{
LineLogged = message;
}
public string VerboseMessageLogged;
public void WriteVerbose(string message)
{
VerboseMessageLogged = message;
}
public string WarningMessageLogged;
public void WriteWarning(string message)
{
WarningMessageLogged = message;
}
}
}

16
src/AddIns/Misc/PackageManagement/Test/Src/Helpers/FakePackageManagementConsoleHost.cs

@ -169,5 +169,21 @@ namespace PackageManagement.Tests.Helpers @@ -169,5 +169,21 @@ namespace PackageManagement.Tests.Helpers
{
FakeFileConflictResolver.AssertWasCalled(resolver => resolver.Dispose());
}
public IDisposable FakeConsoleHostLogger =
MockRepository.GenerateStub<IDisposable>();
public void AssertLoggerIsDisposed()
{
FakeConsoleHostLogger.AssertWasCalled(logger => logger.Dispose());
}
public ICmdletLogger CmdletLoggerUsedToCreateLogger;
public IDisposable CreateLogger(ICmdletLogger logger)
{
CmdletLoggerUsedToCreateLogger = logger;
return FakeConsoleHostLogger;
}
}
}

85
src/AddIns/Misc/PackageManagement/Test/Src/Scripting/PackageManagementConsoleHostLoggerTests.cs

@ -0,0 +1,85 @@ @@ -0,0 +1,85 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Management.Automation;
using ICSharpCode.PackageManagement;
using ICSharpCode.PackageManagement.Scripting;
using NuGet;
using NUnit.Framework;
using PackageManagement.Tests.Helpers;
namespace PackageManagement.Tests.Scripting
{
[TestFixture]
public class PackageManagementConsoleHostLoggerTests
{
FakeCmdletLogger cmdletLogger;
PackageManagementConsoleHostLogger consoleHostLogger;
PackageManagementEvents packageEvents;
void CreateConsoleHostLogger()
{
cmdletLogger = new FakeCmdletLogger();
packageEvents = new PackageManagementEvents();
consoleHostLogger = new PackageManagementConsoleHostLogger(cmdletLogger, packageEvents);
}
[Test]
public void OnPackageOperationMessageLogged_DebugMessage_WrittenAsVerboseMessageToCmdlet()
{
CreateConsoleHostLogger();
packageEvents.OnPackageOperationMessageLogged(MessageLevel.Debug, "test");
Assert.AreEqual("test", cmdletLogger.VerboseMessageLogged);
}
[Test]
public void OnPackageOperationMessageLogged_WarningMessage_WrittenAsWarningMessageToCmdlet()
{
CreateConsoleHostLogger();
packageEvents.OnPackageOperationMessageLogged(MessageLevel.Warning, "test");
Assert.AreEqual("test", cmdletLogger.WarningMessageLogged);
}
[Test]
public void OnPackageOperationMessageLogged_InfoMessage_WrittenAsLineToCmdlet()
{
CreateConsoleHostLogger();
packageEvents.OnPackageOperationMessageLogged(MessageLevel.Info, "test");
Assert.AreEqual("test", cmdletLogger.LineLogged);
}
[Test]
public void OnPackageOperationMessageLogged_ErrorMessage_WrittenAsErrorRecordCmdlet()
{
CreateConsoleHostLogger();
packageEvents.OnPackageOperationMessageLogged(MessageLevel.Error, "test");
Assert.IsNotNull(cmdletLogger.ErrorRecordLogged);
Assert.AreEqual("test", cmdletLogger.ErrorRecordLogged.Exception.Message);
Assert.AreEqual(ErrorCategory.NotSpecified, cmdletLogger.ErrorRecordLogged.CategoryInfo.Category);
}
}
}

24
src/AddIns/Misc/PackageManagement/Test/Src/SolutionPackageRepositoryPathTests.cs

@ -32,8 +32,9 @@ namespace PackageManagement.Tests @@ -32,8 +32,9 @@ namespace PackageManagement.Tests
{
SolutionPackageRepositoryPath repositoryPath;
IProject testProject;
PackageManagementOptions options;
TestablePackageManagementOptions options;
ISolution solution;
FakeSettings settings;
void CreateSolutionPackageRepositoryPath()
{
@ -61,6 +62,12 @@ namespace PackageManagement.Tests @@ -61,6 +62,12 @@ namespace PackageManagement.Tests
void CreateOptions()
{
options = new TestablePackageManagementOptions();
settings = options.FakeSettings;
}
void SolutionNuGetConfigFileHasCustomPackagesPath(string fullPath)
{
settings.SetRepositoryPathSetting(fullPath);
}
[Test]
@ -109,5 +116,20 @@ namespace PackageManagement.Tests @@ -109,5 +116,20 @@ namespace PackageManagement.Tests
Assert.AreEqual(expectedInstallPath, installPath);
}
[Test]
public void PackageRepositoryPath_SolutionHasNuGetFileThatOverridesDefaultPackagesRepositoryPath_OverriddenPathReturned()
{
CreateOptions();
CreateSolution(@"d:\projects\MySolution\MySolution.sln");
options.PackagesDirectory = "Packages";
SolutionNuGetConfigFileHasCustomPackagesPath(@"d:\Team\MyPackages");
CreateSolutionPackageRepositoryPath(solution);
string expectedPath = @"d:\Team\MyPackages";
string path = repositoryPath.PackageRepositoryPath;
Assert.AreEqual(expectedPath, path);
}
}
}

16
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/DesignableItems/BaseLineItem.cs

@ -22,9 +22,8 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems @@ -22,9 +22,8 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems
Point toPoint;
LineCap startLineCap;
LineCap endLineCap;
DashCap dashLineCap;
public BaseLineItem()
{
this.Size = new Size(50,10);
@ -42,8 +41,6 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems @@ -42,8 +41,6 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems
}
// [System.ComponentModel.EditorBrowsableAttribute()]
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e)
{
e.Graphics.SmoothingMode = SmoothingMode.HighQuality;
@ -113,16 +110,5 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems @@ -113,16 +110,5 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems
Invalidate();
}
}
// [Category("Appearance")]
// public DashCap DashLineCap {
// get { return dashLineCap; }
// set {
// dashLineCap = value;
// Invalidate();
// }
// }
}
}

20
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/DesignableItems/BaseRectangleItem.cs

@ -146,17 +146,17 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems @@ -146,17 +146,17 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems
public static GraphicsPath Create(Rectangle rect, int radius, RectangleCorners c)
{ return Create(rect.X, rect.Y, rect.Width, rect.Height, radius, c); }
//
// public static GraphicsPath Create(int x, int y, int width, int height, int radius)
// { return Create(x, y, width, height, radius, RectangleCorners.All); }
public static GraphicsPath Create(int x, int y, int width, int height, int radius)
{ return Create(x, y, width, height, radius, RectangleCorners.All); }
// public static GraphicsPath Create(Rectangle rect, int radius)
// { return Create(rect.X, rect.Y, rect.Width, rect.Height, radius); }
//
// public static GraphicsPath Create(int x, int y, int width, int height)
// { return Create(x, y, width, height, 5); }
public static GraphicsPath Create(Rectangle rect, int radius)
{ return Create(rect.X, rect.Y, rect.Width, rect.Height, radius); }
public static GraphicsPath Create(int x, int y, int width, int height)
{ return Create(x, y, width, height, 5); }
public static GraphicsPath Create(Rectangle rect)
{ return Create(rect.X, rect.Y, rect.Width, rect.Height); }
// public static GraphicsPath Create(Rectangle rect)
// { return Create(rect.X, rect.Y, rect.Width, rect.Height); }
}
}

34
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/DesignableItems/BaseTextItem.cs

@ -10,6 +10,7 @@ using System; @@ -10,6 +10,7 @@ using System;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Design;
using System.Windows;
using ICSharpCode.Reporting.BaseClasses;
using ICSharpCode.Reporting.Globals;
using ICSharpCode.Reporting.Addin.Designer;
@ -31,18 +32,18 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems @@ -31,18 +32,18 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems
StringFormat stringFormat;
StringTrimming stringTrimming;
ContentAlignment contentAlignment;
TextAlignment textAlignment;
public BaseTextItem(){
DefaultSize = GlobalValues.PreferedSize;
Size = GlobalValues.PreferedSize;
BackColor = Color.White;
contentAlignment = ContentAlignment.TopLeft;
textAlignment = TextAlignment.Left;
TypeDescriptor.AddProvider(new TextItemTypeProvider(), typeof(BaseTextItem));
}
// [EditorBrowsableAttribute()]
protected override void OnPaint(System.Windows.Forms.PaintEventArgs e){
base.OnPaint(e);
Draw(e.Graphics);
@ -64,7 +65,8 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems @@ -64,7 +65,8 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems
designTrimmimg = stringTrimming;
}
stringFormat = TextDrawer.BuildStringFormat(designTrimmimg, contentAlignment);
// stringFormat = TextDrawer.BuildStringFormat(designTrimmimg, contentAlignment);
stringFormat = TextDrawer.BuildStringFormat(designTrimmimg, textAlignment);
using (var textBrush = new SolidBrush(ForeColor)) {
TextDrawer.DrawString(graphics, Text, Font, textBrush, ClientRectangle, stringFormat);
}
@ -119,10 +121,9 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems @@ -119,10 +121,9 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems
}
[Category("Appearance")]
[EditorAttribute(typeof(ContentAlignmentEditor),
typeof(UITypeEditor) )]
typeof(UITypeEditor) )]
public ContentAlignment ContentAlignment {
get { return contentAlignment; }
set {
@ -132,18 +133,15 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems @@ -132,18 +133,15 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems
}
[Category("Appearance")]
public TextAlignment TextAlignment {
get { return textAlignment;}
set {textAlignment = value;
Invalidate();}
}
#endregion
// #region RighToLeft
//
// [Category("Appearance")]
// public System.Windows.Forms.RightToLeft RTL
// {
// get { return base.RightToLeft; }
// set { base.RightToLeft = value; }
// }
//
// #endregion
#region DataType
@ -158,10 +156,10 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems @@ -158,10 +156,10 @@ namespace ICSharpCode.Reporting.Addin.DesignableItems
#region Expression
[Browsable(true),
Category("Expression"),
Description("Enter a valid Expression")]
Category("Expression"),
Description("Enter a valid Expression")]
[EditorAttribute(typeof(ExpressionEditor),
typeof(UITypeEditor) )]
typeof(UITypeEditor) )]
public string Expression {get;set;}
#endregion

4
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/DesignerBinding/DesignerBinding.cs

@ -47,9 +47,7 @@ namespace ICSharpCode.Reporting.Addin.DesignerBinding { @@ -47,9 +47,7 @@ namespace ICSharpCode.Reporting.Addin.DesignerBinding {
if (file.IsDirty) {
var reportModel = ReportModelFactory.Create();
var reportFactory = new CreateFormSheetFromModel();
var xml = reportFactory.ToXml(reportModel);
var xml = CreateFormSheetFromModel.ToXml(reportModel);
var doc = new XmlDocument();
doc.LoadXml(xml.ToString());

5
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/DesignerBinding/InternalReportLoader.cs

@ -19,6 +19,7 @@ @@ -19,6 +19,7 @@
using System;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Globalization;
using System.IO;
using System.Windows.Forms;
@ -72,9 +73,9 @@ namespace ICSharpCode.Reporting.Addin.DesignerBinding @@ -72,9 +73,9 @@ namespace ICSharpCode.Reporting.Addin.DesignerBinding
{
string message;
if (generator.ViewContent.PrimaryFile.IsDirty) {
message = String.Format("Create Report <{0}> ...",Path.GetFileName(this.generator.ViewContent.PrimaryFile.FileName));
message = String.Format(CultureInfo.CurrentCulture,"Create Report <{0}> ...",Path.GetFileName(generator.ViewContent.PrimaryFile.FileName));
} else {
message = String.Format("Load Report <{0}> ...",Path.GetFileName(this.generator.ViewContent.PrimaryFile.FileName));
message = String.Format(CultureInfo.CurrentCulture,"Load Report <{0}> ...",Path.GetFileName(generator.ViewContent.PrimaryFile.FileName));
}
SD.StatusBar.SetMessage(message);
}

7
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/Factory/CreateFormSheetFromModel.cs

@ -19,11 +19,10 @@ namespace ICSharpCode.Reporting.Addin.Factory @@ -19,11 +19,10 @@ namespace ICSharpCode.Reporting.Addin.Factory
/// <summary>
/// Description of CreateFormSheetReport.
/// </summary>
class CreateFormSheetFromModel
static class CreateFormSheetFromModel
{
public StringWriter ToXml(IReportModel reportModel) {
public static StringWriter ToXml(IReportModel reportModel) {
int locY = reportModel.ReportSettings.TopMargin;
foreach (var section in reportModel.SectionCollection)
@ -39,7 +38,7 @@ namespace ICSharpCode.Reporting.Addin.Factory @@ -39,7 +38,7 @@ namespace ICSharpCode.Reporting.Addin.Factory
return xml;
}
StringWriter ToXmlInternal(IReportModel model)
static StringWriter ToXmlInternal(IReportModel model)
{
var writer = new StringWriterWithEncoding(System.Text.Encoding.UTF8);
var xml = XmlHelper.CreatePropperWriter(writer);

16
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/Services/HelpService.cs

@ -60,14 +60,14 @@ namespace ICSharpCode.Reporting.Addin.Services @@ -60,14 +60,14 @@ namespace ICSharpCode.Reporting.Addin.Services
{
HelpProvider.ShowHelpByKeyword(helpKeyword);
}
public void ShowGeneralHelp()
{
ShowHelpFromKeyword(generalKeyword);
}
public void ShowHelp()
{
// HelpProvider.ShowHelp(f1Keyword);
}
// public void ShowGeneralHelp()
// {
// ShowHelpFromKeyword(generalKeyword);
// }
// static public void ShowHelp()
// {
//// HelpProvider.ShowHelp(f1Keyword);
// }
public void ShowHelpFromUrl(string helpUrl)
{

2
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/Services/ToolboxService.cs

@ -188,7 +188,7 @@ namespace ICSharpCode.Reporting.Addin.Services @@ -188,7 +188,7 @@ namespace ICSharpCode.Reporting.Addin.Services
// needed for Toolbox drag & drop
if (serializedObject is System.Windows.Forms.IDataObject) {
if (((System.Windows.Forms.IDataObject)serializedObject).GetDataPresent(typeof(ToolboxItem))) {
ToolboxItem item = (ToolboxItem) ((System.Windows.Forms.IDataObject)serializedObject).GetData(typeof(ToolboxItem));
var item = (ToolboxItem) ((System.Windows.Forms.IDataObject)serializedObject).GetData(typeof(ToolboxItem));
// if (host != null) {
// ArrayList list = (ArrayList)toolboxByHost[host];
// if (list != null && list.Contains(item)) {

6
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/TypeProvider/AbstractItemTypeProvider.cs

@ -22,9 +22,9 @@ namespace ICSharpCode.Reporting.Addin.TypeProvider @@ -22,9 +22,9 @@ namespace ICSharpCode.Reporting.Addin.TypeProvider
{
}
public AbstractItemTypeProvider(TypeDescriptionProvider parent): base(parent)
{
}
// public AbstractItemTypeProvider(TypeDescriptionProvider parent): base(parent)
// {
// }
public override ICustomTypeDescriptor GetTypeDescriptor(Type objectType, object instance)

6
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/TypeProvider/TypeProviderHelper.cs

@ -99,6 +99,9 @@ namespace ICSharpCode.Reporting.Addin.TypeProvider @@ -99,6 +99,9 @@ namespace ICSharpCode.Reporting.Addin.TypeProvider
prop = props.Find("ContentAlignment",true);
allProperties.Add(prop);
prop = props.Find("TextAlignment",true);
allProperties.Add(prop);
prop = props.Find("CanGrow",true);
allProperties.Add(prop);
@ -107,9 +110,6 @@ namespace ICSharpCode.Reporting.Addin.TypeProvider @@ -107,9 +110,6 @@ namespace ICSharpCode.Reporting.Addin.TypeProvider
prop = props.Find("DataType",true);
allProperties.Add(prop);
// prop = props.Find("RTL",true);
// allProperties.Add(prop);
}
public static void AddGraphicProperties (List<PropertyDescriptor> allProperties,

6
src/AddIns/Misc/Reporting/ICSharpCode.Reporting.Addin/src/XML/ReportDefinitionParser.cs

@ -22,6 +22,7 @@ using System.ComponentModel; @@ -22,6 +22,7 @@ using System.ComponentModel;
using System.Diagnostics;
using System.Reflection;
using System.Xml;
using System.Xml.XPath;
using ICSharpCode.Reporting.Xml;
@ -102,8 +103,7 @@ namespace ICSharpCode.Reporting.Addin.XML @@ -102,8 +103,7 @@ namespace ICSharpCode.Reporting.Addin.XML
Type t=parent.GetType();
// children of a class must always be properties
foreach(XmlNode child in node.ChildNodes)
{
foreach(XmlNode child in node.ChildNodes){
if (child is XmlElement)
{
string pname=child.LocalName;
@ -220,7 +220,7 @@ namespace ICSharpCode.Reporting.Addin.XML @@ -220,7 +220,7 @@ namespace ICSharpCode.Reporting.Addin.XML
}
}
void SetPropertyToString(object obj, PropertyInfo pi, string value)
static void SetPropertyToString(object obj, PropertyInfo pi, string value)
{
// it's string, so use a type converter.
TypeConverter tc=TypeDescriptor.GetConverter(pi.PropertyType);

8
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/ICSharpCode.Reporting.csproj

@ -91,13 +91,8 @@ @@ -91,13 +91,8 @@
<Compile Include="Src\BaseClasses\TextDrawer.cs" />
<Compile Include="Src\Collections.cs" />
<Compile Include="Src\Configuration\AssemblyInfo.cs" />
<Compile Include="Src\DataManager\DataCollection.cs" />
<Compile Include="Src\DataManager\Listhandling\CollectionDataSource.cs" />
<Compile Include="Src\DataManager\Listhandling\IndexList.cs" />
<Compile Include="Src\DataSource\Comparer\BaseComparer.cs" />
<Compile Include="Src\DataSource\Comparer\GroupComparer.cs" />
<Compile Include="Src\DataSource\Comparer\SortComparer.cs" />
<Compile Include="Src\DataSource\Comparer\SortExtension.cs" />
<Compile Include="Src\DataSource\DataCollection.cs" />
<Compile Include="Src\DataSource\ExtendedPropertyDescriptor.cs" />
<Compile Include="Src\DataSource\ExtendedTypeDescriptor.cs" />
<Compile Include="Src\DataSource\FieldMemberAccessor.cs" />
@ -196,7 +191,6 @@ @@ -196,7 +191,6 @@
<Compile Include="Src\Xml\MycroParser.cs" />
</ItemGroup>
<ItemGroup>
<Folder Include="Src\DataSource\Comparer" />
<Folder Include="Src\Exporter\Visitors" />
<Folder Include="Src\Expressions\Irony" />
<Folder Include="Src\Expressions\Irony\Ast" />

5
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/Arrange/ArrangeStrategy.cs

@ -58,7 +58,6 @@ namespace ICSharpCode.Reporting.Arrange @@ -58,7 +58,6 @@ namespace ICSharpCode.Reporting.Arrange
{
var containerRectangle = container.DisplayRectangle;
Rectangle elementRectangle = Rectangle.Empty;
foreach (var element in container.ExportedItems) {
var con = element as IExportContainer;
if (con != null) {
@ -76,9 +75,7 @@ namespace ICSharpCode.Reporting.Arrange @@ -76,9 +75,7 @@ namespace ICSharpCode.Reporting.Arrange
containerRectangle = new Rectangle(containerRectangle.Left,
containerRectangle.Top ,
containerRectangle.Width,
element.Location.Y + elementRectangle.Size.Height + 5);
// containerRectangle = Rectangle.Union(containerRectangle,elementRectangle);
element.Location.Y + elementRectangle.Size.Height + 5);
}
}
return containerRectangle.Size;

71
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/BaseClasses/TextDrawer.cs

@ -9,20 +9,15 @@ @@ -9,20 +9,15 @@
using System;
using System.Drawing;
using System.Drawing.Text;
using System.Windows;
namespace ICSharpCode.Reporting.BaseClasses
{
/// <summary>
/// Description of TextDrawer.
/// </summary>
public sealed class TextDrawer
public static class TextDrawer
{
private TextDrawer()
{
}
public static void DrawString(Graphics graphics,string text,
Font font,Brush brush,
RectangleF rectangle,
@ -38,41 +33,40 @@ namespace ICSharpCode.Reporting.BaseClasses @@ -38,41 +33,40 @@ namespace ICSharpCode.Reporting.BaseClasses
rectangle,
format);
}
public static void DrawString (Graphics graphics,string text)
{
if (graphics == null) {
throw new ArgumentNullException("graphics");
public static StringFormat BuildStringFormat(StringTrimming stringTrimming,TextAlignment alignment){
StringFormat format = StringFormat.GenericTypographic;
format.Trimming = stringTrimming;
format.FormatFlags = StringFormatFlags.LineLimit;
switch (alignment) {
case TextAlignment.Left:{
format.Alignment = StringAlignment.Near;
format.LineAlignment = StringAlignment.Near;
return format;
}
case TextAlignment.Center:{
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Near;
return format;
}
case TextAlignment.Right:{
format.Alignment = StringAlignment.Far;
format.LineAlignment = StringAlignment.Near;
return format;
}
case TextAlignment.Justify:{
format.Alignment = StringAlignment.Center;
format.LineAlignment = StringAlignment.Near;
return format;
}
}
// if (decorator == null) {
// throw new ArgumentNullException("decorator");
// }
// StringFormat stringFormat = BuildStringFormat(decorator.StringTrimming,decorator.ContentAlignment);
//
// if (decorator.RightToLeft ==System.Windows.Forms.RightToLeft.Yes) {
// stringFormat.FormatFlags = stringFormat.FormatFlags | StringFormatFlags.DirectionRightToLeft;
// }
var formattedString = text;
// if (! String.IsNullOrEmpty(decorator.FormatString)) {
// formattedString = StandardFormatter.FormatOutput(text,decorator.FormatString,decorator.DataType,String.Empty);
// }
graphics.TextRenderingHint = TextRenderingHint.AntiAlias;
// graphics.DrawString (formattedString,decorator.Font,
// new SolidBrush(decorator.ForeColor),
// new Rectangle(decorator.Location.X,
// decorator.Location.Y,
// decorator.Size.Width,
// decorator.Size.Height),
// stringFormat);
return format;
}
/*
public static StringFormat BuildStringFormat(StringTrimming stringTrimming,ContentAlignment alignment)
{
StringFormat format = StringFormat.GenericTypographic;
@ -139,5 +133,6 @@ namespace ICSharpCode.Reporting.BaseClasses @@ -139,5 +133,6 @@ namespace ICSharpCode.Reporting.BaseClasses
format.LineAlignment = StringAlignment.Far;
return format;
}
*/
}
}

12
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/Collections.cs

@ -52,9 +52,6 @@ namespace ICSharpCode.Reporting @@ -52,9 +52,6 @@ namespace ICSharpCode.Reporting
public class GroupColumnCollection: SortColumnCollection
{
public GroupColumnCollection()
{
}
public new AbstractColumn Find (string columnName)
{
@ -67,12 +64,7 @@ namespace ICSharpCode.Reporting @@ -67,12 +64,7 @@ namespace ICSharpCode.Reporting
}
public class ParameterCollection: Collection<BasicParameter>{
public ParameterCollection()
{
}
public class ParameterCollection: Collection<BasicParameter>{
public BasicParameter Find (string parameterName)
{
@ -85,7 +77,7 @@ namespace ICSharpCode.Reporting @@ -85,7 +77,7 @@ namespace ICSharpCode.Reporting
public static CultureInfo Culture
{
get { return System.Globalization.CultureInfo.CurrentCulture; }
get { return CultureInfo.CurrentCulture; }
}

3
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/DataCollection.cs → src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataManager/DataCollection.cs

@ -24,8 +24,9 @@ using System.ComponentModel; @@ -24,8 +24,9 @@ using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using ICSharpCode.Reporting.DataSource;
namespace ICSharpCode.Reporting.DataSource
namespace ICSharpCode.Reporting.DataManager
{
/// <summary>
/// Description of DataCollection.

22
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataManager/Listhandling/CollectionDataSource.cs

@ -44,7 +44,6 @@ namespace ICSharpCode.Reporting.DataManager.Listhandling @@ -44,7 +44,6 @@ namespace ICSharpCode.Reporting.DataManager.Listhandling
{
readonly DataCollection<object> baseList;
readonly ReportSettings reportSettings;
// readonly Type elementType;
readonly PropertyDescriptorCollection listProperties;
@ -61,24 +60,7 @@ namespace ICSharpCode.Reporting.DataManager.Listhandling @@ -61,24 +60,7 @@ namespace ICSharpCode.Reporting.DataManager.Listhandling
this.listProperties = this.baseList.GetItemProperties(null);
OrderGroup = OrderGroup.AsIs;
}
[Obsolete("use public CollectionDataSource(IEnumerable list, ReportSettings reportSettings")]
public CollectionDataSource(IEnumerable list, Type elementType, ReportSettings reportSettings)
{
if (list == null)
throw new ArgumentNullException("list");
if (reportSettings == null)
throw new ArgumentNullException("reportSettings");
baseList = CreateBaseList(list);
CurrentList = baseList;
this.reportSettings = reportSettings;
this.listProperties = this.baseList.GetItemProperties(null);
OrderGroup = OrderGroup.AsIs;
}
public Collection<AbstractColumn> AvailableFields {
get {
@ -176,7 +158,7 @@ namespace ICSharpCode.Reporting.DataManager.Listhandling @@ -176,7 +158,7 @@ namespace ICSharpCode.Reporting.DataManager.Listhandling
public void Fill (List<IPrintableObject> collection, object current) {
Current = current;
foreach (var element in collection) {
foreach (var element in collection) {
var container = element as ReportContainer;
if (container != null) {
FillFromList(container.Items);

102
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/Comparer/BaseComparer.cs

@ -1,102 +0,0 @@ @@ -1,102 +0,0 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.ObjectModel;
using ICSharpCode.Reporting.BaseClasses;
namespace ICSharpCode.Reporting.DataSource.Comparer
{
/// <summary>
/// Description of BaseComparer.
/// </summary>
public class BaseComparer : IComparable {
private int listIndex;
private object[] objectArray;
/// <summary>
/// Default constructor - initializes all fields to default values
/// </summary>
public BaseComparer(Collection<AbstractColumn> columnCollection , int listIndex, object[] values) {
this.ColumnCollection = columnCollection;
this.listIndex = listIndex;
this.objectArray = values;
}
/// <summary>
/// Interface method from IComparable
/// </summary>
/// <remarks>
/// Interface method from IComparable
///
/// </remarks>
/// <param name='obj'>a <see cref="BaseComparer"></see></param>
public virtual int CompareTo(object obj) {
return 0;
}
/// <summary>
/// Ausgeben der Werte als Pseudo-CSV
/// </summary>
public override string ToString()
{
System.Text.StringBuilder builder = new System.Text.StringBuilder();
builder.AppendFormat("{0};", this.listIndex);
foreach (object value in objectArray)
{
if (value == null || value == DBNull.Value)
{
builder.AppendFormat("<NULL>");
}
else if (value.GetType() == typeof(string))
{
builder.AppendFormat("\"{0}\"", (string)value);
}
else if (value is IFormattable)
{
builder.AppendFormat("{0}", ((IFormattable)value).ToString("g", System.Globalization.CultureInfo.InvariantCulture));
}
else
{
builder.AppendFormat("[{0}]", value.ToString());
}
builder.Append(';');
}
return builder.ToString();
}
public int ListIndex {
get {
return listIndex;
}
}
public object[] ObjectArray {
get {
return objectArray;
}
}
public Collection<AbstractColumn> ColumnCollection {get;private set;}
}
}

115
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/Comparer/SortComparer.cs

@ -1,115 +0,0 @@ @@ -1,115 +0,0 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using System;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Globalization;
using ICSharpCode.Reporting.BaseClasses;
using ICSharpCode.Reporting.Items;
namespace ICSharpCode.Reporting.DataSource.Comparer
{
/// <summary>
/// Description of SortComparer.
/// </summary>
public class SortComparer : BaseComparer {
public SortComparer(Collection<AbstractColumn> owner, int listIndex, object[] values):base(owner,listIndex,values)
{
}
internal int CompareTo(SortComparer value)
{
// we shouldn't get to this point
if (value == null)
throw new ArgumentNullException("value");
if (value.ObjectArray.Length != base.ObjectArray.Length)
throw new InvalidOperationException();
int compare = 0;
for (int index = 0; index < base.ObjectArray.Length; index++)
{
object leftValue = base.ObjectArray[index];
object rightValue = value.ObjectArray[index];
// Indizes sind hier deckungsgleich
SortColumn sortColumn = (SortColumn)base.ColumnCollection[index];
bool descending = (sortColumn.SortDirection == ListSortDirection.Descending);
// null means equl
if (leftValue == null || leftValue == System.DBNull.Value)
{
if (rightValue != null && rightValue != System.DBNull.Value)
{
return (descending) ? 1 : -1;
}
// Beide Null
continue;
}
if (rightValue == null || rightValue == System.DBNull.Value)
{
return (descending) ? -1 : 1;
}
if (leftValue.GetType() != rightValue.GetType()){
string s = String.Format(CultureInfo.CurrentCulture,
"{0} {1} {2}",this.GetType().ToString(),
leftValue.GetType().ToString(),
rightValue.GetType().ToString());
throw new ArgumentException(s);
}
if (leftValue.GetType() == typeof(string))
{
compare = String.Compare((string)leftValue, (string)rightValue,
!sortColumn.CaseSensitive, CultureInfo.CurrentCulture);
}
else
{
compare = ((IComparable)leftValue).CompareTo(rightValue);
}
// Sind ungleich, tauschen je nach Richtung
if (compare != 0)
{
return (descending) ? -compare : compare;
}
}
// Gleich Werte, dann Index bercksichtigen
return this.ListIndex.CompareTo(value.ListIndex);
}
public override int CompareTo(object obj) {
base.CompareTo(obj);
return this.CompareTo((SortComparer)obj);
}
}
}

3
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/ExtendedPropertyDescriptor.cs

@ -20,6 +20,7 @@ using System; @@ -20,6 +20,7 @@ using System;
using System.Collections;
using System.ComponentModel;
using System.Reflection;
using ICSharpCode.Reporting.DataManager;
namespace ICSharpCode.Reporting.DataSource
{
@ -30,7 +31,7 @@ namespace ICSharpCode.Reporting.DataSource @@ -30,7 +31,7 @@ namespace ICSharpCode.Reporting.DataSource
{
Type componentType;
Type propertyType;
readonly Type propertyType;
PropertyInfo prop;
public ExtendedPropertyDescriptor (string name, Type componentType, Type propertyType)

8
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/ExtendedTypeDescriptor.cs

@ -28,9 +28,9 @@ namespace ICSharpCode.Reporting.DataSource @@ -28,9 +28,9 @@ namespace ICSharpCode.Reporting.DataSource
/// </summary>
class ExtendedTypeDescriptor
{
private static Hashtable collections = new Hashtable();
static Hashtable collections = new Hashtable();
private static bool IsAllowedProperty(string name)
static bool IsAllowedProperty(string name)
{
return true; // alle erlaubt
}
@ -57,7 +57,7 @@ namespace ICSharpCode.Reporting.DataSource @@ -57,7 +57,7 @@ namespace ICSharpCode.Reporting.DataSource
}
}
PropertyDescriptor[] descriptors = new PropertyDescriptor[l];
var descriptors = new PropertyDescriptor[l];
int j = 0;
foreach(PropertyInfo pinfo in allProps)
@ -67,7 +67,7 @@ namespace ICSharpCode.Reporting.DataSource @@ -67,7 +67,7 @@ namespace ICSharpCode.Reporting.DataSource
descriptors[j++] = new ExtendedPropertyDescriptor(pinfo.Name, memberType, pinfo.PropertyType);
}
}
PropertyDescriptorCollection result = new PropertyDescriptorCollection(descriptors);
var result = new PropertyDescriptorCollection(descriptors);
collections.Add(memberType, result);
return result;
}

2
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/DataSource/PropertyMemberAccessore.cs

@ -33,7 +33,7 @@ namespace ICSharpCode.Reporting.DataSource @@ -33,7 +33,7 @@ namespace ICSharpCode.Reporting.DataSource
public class PropertyMemberAccessor : IMemberAccessor
{
private readonly PropertyInfo _prop;
readonly PropertyInfo _prop;
public PropertyMemberAccessor(PropertyInfo prop)
{

4
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/Exporter/Visitors/AbstractVisitor.cs

@ -85,12 +85,12 @@ namespace ICSharpCode.Reporting.Exporter.Visitors @@ -85,12 +85,12 @@ namespace ICSharpCode.Reporting.Exporter.Visitors
protected Collection<ExportPage> Pages {get; private set;}
protected bool IsContainer (IExportColumn column) {
static protected bool IsContainer (IExportColumn column) {
return (column is ExportContainer)|| (column is GraphicsContainer);
}
protected bool IsGraphicsContainer (IExportColumn column) {
static protected bool IsGraphicsContainer (IExportColumn column) {
return column is GraphicsContainer;
}
}

2
src/AddIns/Misc/Reporting/ICSharpCode.Reporting/Src/Exporter/Visitors/DebugVisitor.cs

@ -48,8 +48,6 @@ namespace ICSharpCode.Reporting.Exporter.Visitors @@ -48,8 +48,6 @@ namespace ICSharpCode.Reporting.Exporter.Visitors
public override void Visit(ExportLine exportGraphics)
{
// base.Visit(exportGraphics);
Console.WriteLine("Line from {0} size {1}",exportGraphics.Location,exportGraphics.Size.Width);
}
}
}

Some files were not shown because too many files have changed in this diff Show More

Loading…
Cancel
Save