diff options
author | Lluis Sanchez Gual <lluis@xamarin.com> | 2013-09-19 11:41:17 +0400 |
---|---|---|
committer | Lluis Sanchez Gual <lluis@xamarin.com> | 2013-09-19 11:41:17 +0400 |
commit | 9d473f5e2bd7a829ad634b5210c18648b0773f9f (patch) | |
tree | 15d065c272cdc188c221fd8b5b3e9c1d2a128816 | |
parent | 098e6a947ca646b7c74cb411c3d50e3c365cfb82 (diff) | |
parent | 0f0e889b869895901a18132e995167b020401f8a (diff) |
Merge remote-tracking branch 'origin/master' into fsharp
Conflicts:
version-checks
120 files changed, 1957 insertions, 1188 deletions
@@ -270,7 +270,7 @@ fi if test `uname` = "Darwin"; then if test "x$BUILD_REVISION" != "x" -o "x$DYLD_FALLBACK_LIBRARY_PATH" = "x"; then export DYLD_FALLBACK_LIBRARY_PATH="/Library/Frameworks/Mono.framework/Versions/Current/lib:/lib:/usr/lib" - export PATH="$PATH:/Library/Frameworks/Mono.framework/Versions/Current/bin" + export PATH="/Library/Frameworks/Mono.framework/Versions/Current/bin:$PATH" export ACLOCAL_FLAGS="-I /Library/Frameworks/Mono.framework/Versions/Current/share/aclocal" fi fi diff --git a/extras/MonoDevelop.AddinAuthoring/MonoDevelop.AddinAuthoring.NodeBuilders/ProjectFolderNodeBuilderExtension.cs b/extras/MonoDevelop.AddinAuthoring/MonoDevelop.AddinAuthoring.NodeBuilders/ProjectFolderNodeBuilderExtension.cs index 56042df367..e4dddd8826 100644 --- a/extras/MonoDevelop.AddinAuthoring/MonoDevelop.AddinAuthoring.NodeBuilders/ProjectFolderNodeBuilderExtension.cs +++ b/extras/MonoDevelop.AddinAuthoring/MonoDevelop.AddinAuthoring.NodeBuilders/ProjectFolderNodeBuilderExtension.cs @@ -61,7 +61,7 @@ namespace MonoDevelop.AddinAuthoring.NodeBuilders base.GetNodeAttributes (parentNode, dataObject, ref attributes); if (dataObject is ProjectFile) { string fname = ((ProjectFile)dataObject).Name; - if (fname.EndsWith (".addin.xml") || fname.EndsWith (".addin")) { + if (fname.EndsWith (".addin.xml", StringComparison.Ordinal) || fname.EndsWith (".addin", StringComparison.Ordinal)) { if (!(parentNode.DataItem is AddinData)) { DotNetProject dp = (DotNetProject) parentNode.GetParentDataItem (typeof(DotNetProject), true); if (dp != null && dp.GetAddinData () != null) { diff --git a/main/build/MacOSX/Makefile.am b/main/build/MacOSX/Makefile.am index 7202ba52ac..805ccc0adb 100644 --- a/main/build/MacOSX/Makefile.am +++ b/main/build/MacOSX/Makefile.am @@ -32,8 +32,8 @@ render.exe: render.cs dmg: render.exe app ./make-dmg-bundle.sh -monostub: monostub.m - gcc -Wall -mmacosx-version-min=10.6 -m32 -o monostub monostub.m $(MONOSTUB_EXTRA_SOURCES) -framework AppKit +monostub: monostub.m $(MONOSTUB_EXTRA_SOURCES) + gcc -Wall -mmacosx-version-min=10.6 -m32 -o $@ $^ -framework AppKit clean-local: rm -rf MonoDevelop.app diff --git a/main/external/debugger-libs b/main/external/debugger-libs -Subproject 97ecbbcc25130edfc8cc6bd8c860764f3fde14c +Subproject ff2500d666b92dbf1f68ae029e5a6ee9a53b106 diff --git a/main/external/maccore b/main/external/maccore -Subproject 69d1a5109b0068ead5bc779698c93691ff56cba +Subproject c56ff209497cf0fbbfeff3f5696eda58670facf diff --git a/main/external/mono-addins b/main/external/mono-addins -Subproject 32ac38a32e57a1de31797dc748b465b55b5d12a +Subproject 0a1c0a06ed7381906a27466afa91bd824f75de0 diff --git a/main/external/monomac b/main/external/monomac -Subproject 33ca30e49d44d9c1dca4a5eebedeae167c01a8f +Subproject 6ba8ba62e3d07de3bc28b268a18b47193041277 diff --git a/main/external/ngit b/main/external/ngit -Subproject bd2228ec92581736cfda29189ef61077321e920 +Subproject 4f3290d81529f5ebc5b0b51d1bb7a1eb727537a diff --git a/main/external/nrefactory b/main/external/nrefactory -Subproject 45ea8ce7bf1bad6e4f361c154b5536e3293badc +Subproject 4af0b962e89d8e3be176161533ca1f7ae5a09d8 diff --git a/main/src/addins/AspNet/MonoDevelop.AspNet/MonoDevelop.AspNet.StateEngine/AspNetExpressionState.cs b/main/src/addins/AspNet/MonoDevelop.AspNet/MonoDevelop.AspNet.StateEngine/AspNetExpressionState.cs index 6b50a275b8..8ba27eb549 100644 --- a/main/src/addins/AspNet/MonoDevelop.AspNet/MonoDevelop.AspNet.StateEngine/AspNetExpressionState.cs +++ b/main/src/addins/AspNet/MonoDevelop.AspNet/MonoDevelop.AspNet.StateEngine/AspNetExpressionState.cs @@ -45,8 +45,7 @@ namespace MonoDevelop.AspNet.StateEngine AddExpressionNode (c, context); } else if (c == '%') { - if (context.StateTag != PERCENT) - context.StateTag = PERCENT; + context.StateTag = PERCENT; } else if (c == '>') { if (context.StateTag == PERCENT) { @@ -54,8 +53,9 @@ namespace MonoDevelop.AspNet.StateEngine expr.End (context.Location); if (context.BuildTree) { XObject ob = context.Nodes.Peek (); - if (ob is XContainer) { - ((XContainer)ob).AddChildNode (expr); + var xc = ob as XContainer; + if (xc != null) { + xc.AddChildNode (expr); } //FIXME: add to other kinds of node, e.g. if used within a tag } @@ -91,7 +91,7 @@ namespace MonoDevelop.AspNet.StateEngine break; // RENDER BLOCK default: - context.Nodes.Push (new AspNetRenderBlock (context.LocationMinus (2))); + context.Nodes.Push (new AspNetRenderBlock (context.LocationMinus (3))); break; } } diff --git a/main/src/addins/CSharpBinding/CSharpBinding.addin.xml b/main/src/addins/CSharpBinding/CSharpBinding.addin.xml index 27a932450d..d40ae256cd 100644 --- a/main/src/addins/CSharpBinding/CSharpBinding.addin.xml +++ b/main/src/addins/CSharpBinding/CSharpBinding.addin.xml @@ -5,7 +5,8 @@ <Extension path = "/MonoDevelop/Ide/Commands"> <Command id = "MonoDevelop.CodeGeneration.CodeGenerationCommands.ShowCodeGenerationWindow" _label = "S_how Code Generation Window" - shortcut = "Alt|Insert" /> + shortcut = "Alt|Insert" + macShortcut = "Meta|I" /> </Extension> <Extension path = "/MonoDevelop/ProjectModel/MSBuildItemTypes"> @@ -191,7 +192,11 @@ _description = "Converts constant fields to enumeration" class = "MonoDevelop.CSharp.Refactoring.CodeActions.ConvertToEnumAction" /> </Extension> - + + <Extension path = "/MonoDevelop/Refactoring/CodeIssues"> + <CodeIssue mimeType="text/x-csharp" severity = "Error" class="MonoDevelop.CSharp.Refactoring.CodeIssues.MonoTODOIssue"/> + </Extension> + <Extension path = "/MonoDevelop/Ide/TextEditorResolver"> <Resolver class = "MonoDevelop.CSharp.Resolver.TextEditorResolverProvider" mimeType="text/x-csharp" /> </Extension> @@ -226,6 +231,7 @@ <Class class = "MonoDevelop.CodeGeneration.ReadonlyPropertyGenerator" /> <Class class = "MonoDevelop.CodeGeneration.PropertyGenerator" /> <Class class = "MonoDevelop.CodeGeneration.ImplementInterfaceMembersGenerator" /> + <Class class = "MonoDevelop.CodeGeneration.ExportCodeGenerator" /> <Class class = "MonoDevelop.CodeGeneration.PartialGenerator" /> <Class class = "MonoDevelop.CodeGeneration.OverrideMembersGenerator" /> <Class class = "MonoDevelop.CodeGeneration.ToStringGenerator" /> diff --git a/main/src/addins/CSharpBinding/CSharpBinding.csproj b/main/src/addins/CSharpBinding/CSharpBinding.csproj index 2ff9161daa..eb36796ab2 100644 --- a/main/src/addins/CSharpBinding/CSharpBinding.csproj +++ b/main/src/addins/CSharpBinding/CSharpBinding.csproj @@ -321,6 +321,9 @@ <Compile Include="MonoDevelop.CSharp.Refactoring.CodeIssues\BaseNRefactoryIssueProvider.cs" /> <Compile Include="MonoDevelop.CSharp.CodeGeneration\PartialGenerator.cs" /> <Compile Include="AddinInfo.cs" /> + <Compile Include="MonoDevelop.CSharp.Refactoring.CodeIssues\Issues\MonoTODOIssue.cs" /> + <Compile Include="MonoDevelop.CSharp.Refactoring\CSharpCodeGenerationService.cs" /> + <Compile Include="MonoDevelop.CSharp.CodeGeneration\ExportCodeGenerator.cs" /> </ItemGroup> <ItemGroup> <None Include="Makefile.am" /> @@ -343,5 +346,6 @@ <Folder Include="MonoDevelop.CSharp.Refactoring.CodeIssues\NamingInspection\" /> <Folder Include="MonoDevelop.CSharp.Tooltips\" /> <Folder Include="MonoDevelop.CSharp.UnitTests\" /> + <Folder Include="MonoDevelop.CSharp.Refactoring.CodeIssues\Issues\" /> </ItemGroup> </Project> diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/AbstractGenerateAction.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/AbstractGenerateAction.cs index 999e69c0c8..c3b8a772ed 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/AbstractGenerateAction.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/AbstractGenerateAction.cs @@ -36,7 +36,7 @@ using MonoDevelop.Ide.TypeSystem; namespace MonoDevelop.CodeGeneration { - abstract class AbstractGenerateAction : IGenerateAction + public abstract class AbstractGenerateAction : IGenerateAction { readonly TreeStore store = new TreeStore (typeof(bool), typeof(Gdk.Pixbuf), typeof(string), typeof(object)); readonly CodeGenerationOptions options; diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CodeGenerationOptions.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CodeGenerationOptions.cs index 52cfe816b6..73032bb2d2 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CodeGenerationOptions.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/CodeGenerationOptions.cs @@ -37,7 +37,7 @@ using System.Threading; namespace MonoDevelop.CodeGeneration { - class CodeGenerationOptions + public class CodeGenerationOptions { public Document Document { get; diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ExportCodeGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ExportCodeGenerator.cs new file mode 100644 index 0000000000..473a4a3715 --- /dev/null +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ExportCodeGenerator.cs @@ -0,0 +1,142 @@ +// +// ExportCodeGenerator.cs +// +// Author: +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) +// +// 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 Gtk; +using System.Collections.Generic; +using ICSharpCode.NRefactory.CSharp; +using MonoDevelop.Core; +using ICSharpCode.NRefactory.TypeSystem; +using System; +using System.Linq; +using ICSharpCode.NRefactory.CSharp.Refactoring; +using MonoDevelop.CSharp.Refactoring.CodeActions; + +namespace MonoDevelop.CodeGeneration +{ + class ExportCodeGenerator : ICodeGenerator + { + + #region ICodeGenerator implementation + + bool ICodeGenerator.IsValid (CodeGenerationOptions options) + { + return new ExportMethods (options).IsValid (); + } + + IGenerateAction ICodeGenerator.InitalizeSelection (CodeGenerationOptions options, TreeView treeView) + { + var exportMethods = new ExportMethods (options); + exportMethods.Initialize (treeView); + return exportMethods; + } + + string ICodeGenerator.Icon { + get { + return "md-method"; + } + } + + string ICodeGenerator.Text { + get { + return GettextCatalog.GetString ("Implement protocol methods"); + } + } + + string ICodeGenerator.GenerateDescription { + get { + return GettextCatalog.GetString ("Select methods to implement"); + } + } + + #endregion + + class ExportMethods : AbstractGenerateAction + { + public ExportMethods (CodeGenerationOptions options) : base (options) + { + } + + protected override IEnumerable<object> GetValidMembers () + { + var type = Options.EnclosingType; + if (type == null || Options.EnclosingMember != null) + yield break; + foreach (var t in type.DirectBaseTypes) { + foreach (var attrs in t.GetDefinition ().GetAttributes ()) { + if (attrs.AttributeType.Name != "ProtocolAttribute" || attrs.AttributeType.Namespace != "MonoTouch.Foundation") + continue; + foreach (var na in attrs.NamedArguments) { + if (na.Key.Name != "Name") + continue; + string name = na.Value.ConstantValue as string; + if (name == null) + break; + var protocolType = Options.Document.Compilation.FindType (new FullTypeName (new TopLevelTypeName (t.Namespace, name))); + if (protocolType == null) + break; + foreach (var member in protocolType.GetMembers ()) { + if (member.Attributes.Any (a => a.AttributeType.Name == "ExportAttribute" && a.AttributeType.Namespace == "MonoTouch.Foundation")) + yield return member; + } + } + } + } + } + + protected override IEnumerable<string> GenerateCode (List<object> includedMembers) + { + var generator = Options.CreateCodeGenerator (); + generator.AutoIndent = false; + var ctx = new MDRefactoringContext (Options.Document, Options.Document.Editor.Caret.Location); + var builder = ctx.CreateTypeSystemAstBuilder (); + + foreach (IMember member in includedMembers) { + var method = builder.ConvertEntity (member) as MethodDeclaration; + method.Body = new BlockStatement () { + new ThrowStatement (new ObjectCreateExpression (ctx.CreateShortType ("System", "NotImplementedException"))) + }; + var astType = ctx.CreateShortType ("MonoTouch.Foundation", "ExportAttribute"); + if (astType is SimpleType) { + astType = new SimpleType ("Export"); + } else { + astType = new MemberType (new MemberType (new SimpleType ("MonoTouch"), "Foundation"), "Export"); + } + + var attr = new ICSharpCode.NRefactory.CSharp.Attribute { + Type = astType, + }; + method.Modifiers &= ~Modifiers.Virtual; + var exportAttribute = member.GetAttribute (new FullTypeName (new TopLevelTypeName ("MonoTouch.Foundation", "ExportAttribute"))); + attr.Arguments.Add (new PrimitiveExpression (exportAttribute.PositionalArguments.First ().ConstantValue)); + method.Attributes.Add (new AttributeSection { + Attributes = { attr } + }); + yield return method.ToString (); + } + } + } + } +} + diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ICodeGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ICodeGenerator.cs index 334bff1fbf..b70422665b 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ICodeGenerator.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ICodeGenerator.cs @@ -31,7 +31,7 @@ using Mono.Addins; namespace MonoDevelop.CodeGeneration { - interface ICodeGenerator + public interface ICodeGenerator { string Icon { get; @@ -50,7 +50,7 @@ namespace MonoDevelop.CodeGeneration IGenerateAction InitalizeSelection (CodeGenerationOptions options, Gtk.TreeView treeView); } - interface IGenerateAction + public interface IGenerateAction { void GenerateCode (); } diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ImplementInterfaceMembersGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ImplementInterfaceMembersGenerator.cs index e992e56fac..7646b4002f 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ImplementInterfaceMembersGenerator.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.CodeGeneration/ImplementInterfaceMembersGenerator.cs @@ -81,7 +81,8 @@ namespace MonoDevelop.CodeGeneration foreach (var baseType in Options.EnclosingType.DirectBaseTypes) { if (baseType.Kind != TypeKind.Interface) continue; - foreach (var t in ICSharpCode.NRefactory.CSharp.Refactoring.ImplementInterfaceAction.CollectMembersToImplement (type, baseType, false)) { + bool ifm; + foreach (var t in ICSharpCode.NRefactory.CSharp.Refactoring.ImplementInterfaceAction.CollectMembersToImplement (type, baseType, false, out ifm)) { yield return t; } } diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs index 647a789bc3..60291ee56b 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Formatting/CSharpTextEditorIndentation.cs @@ -41,6 +41,7 @@ using System.Linq; using System.Text; using ICSharpCode.NRefactory.CSharp; using MonoDevelop.Ide; +using ICSharpCode.NRefactory; namespace MonoDevelop.CSharp.Formatting { @@ -96,20 +97,6 @@ namespace MonoDevelop.CSharp.Formatting }; } - bool IsPreprocessorDirective (DocumentLine documentLine) - { - int o = documentLine.Offset; - for (int i = 0; i < documentLine.Length; i++) { - char ch = Editor.GetCharAt (o++); - if (ch == '#') - return true; - if (!char.IsWhiteSpace (ch)) { - return false; - } - } - return false; - } - internal void SafeUpdateIndentEngine (int offset) { try { @@ -130,26 +117,21 @@ namespace MonoDevelop.CSharp.Formatting var curLineOffset = curLine.Offset; SafeUpdateIndentEngine (curLineOffset); if (!stateTracker.IsInsideOrdinaryCommentOrString) { - // The Indent engine doesn't really handle pre processor directives very well. - if (IsPreprocessorDirective (curLine)) { - Editor.Replace (curLineOffset, curLine.Length, stateTracker.NextLineIndent + Editor.GetTextAt (curLine).TrimStart ()); - } else { - int pos = curLineOffset; - string curIndent = curLine.GetIndentation (textEditorData.Document); - int nlwsp = curIndent.Length; - - if (!stateTracker.LineBeganInsideMultiLineComment || (nlwsp < curLine.LengthIncludingDelimiter && textEditorData.Document.GetCharAt (curLineOffset + nlwsp) == '*')) { - // Possibly replace the indent - SafeUpdateIndentEngine (curLineOffset + curLine.Length); - string newIndent = stateTracker.ThisLineIndent; - if (newIndent != curIndent) { - if (CompletionWindowManager.IsVisible) { - if (pos < CompletionWindowManager.CodeCompletionContext.TriggerOffset) - CompletionWindowManager.CodeCompletionContext.TriggerOffset -= nlwsp; - } - textEditorData.Replace (pos, nlwsp, newIndent); - textEditorData.Document.CommitLineUpdate (textEditorData.Caret.Line); + int pos = curLineOffset; + string curIndent = curLine.GetIndentation (textEditorData.Document); + int nlwsp = curIndent.Length; + + if (!stateTracker.LineBeganInsideMultiLineComment || (nlwsp < curLine.LengthIncludingDelimiter && textEditorData.Document.GetCharAt (curLineOffset + nlwsp) == '*')) { + // Possibly replace the indent + SafeUpdateIndentEngine (curLineOffset + curLine.Length); + string newIndent = stateTracker.ThisLineIndent; + if (newIndent != curIndent) { + if (CompletionWindowManager.IsVisible) { + if (pos < CompletionWindowManager.CodeCompletionContext.TriggerOffset) + CompletionWindowManager.CodeCompletionContext.TriggerOffset -= nlwsp; } + textEditorData.Replace (pos, nlwsp, newIndent); + textEditorData.Document.CommitLineUpdate (textEditorData.Caret.Line); } } } @@ -184,7 +166,8 @@ namespace MonoDevelop.CSharp.Formatting textEditorData.Document.TextReplaced += HandleTextReplaced; textEditorData.Paste += HandleTextPaste; } - IdeApp.Workspace.ActiveConfigurationChanged += HandleTextOptionsChanged; + if (IdeApp.Workspace != null) + IdeApp.Workspace.ActiveConfigurationChanged += HandleTextOptionsChanged; } @@ -196,7 +179,7 @@ namespace MonoDevelop.CSharp.Formatting IStateMachineIndentEngine indentEngine; try { var csharpIndentEngine = new CSharpIndentEngine (textEditorData.Document, options, policy); - csharpIndentEngine.EnableCustomIndentLevels = true; + //csharpIndentEngine.EnableCustomIndentLevels = true; foreach (var symbol in MonoDevelop.CSharp.Highlighting.CSharpSyntaxMode.GetDefinedSymbols (document.Project)) { csharpIndentEngine.DefineSymbol (symbol); } @@ -231,15 +214,17 @@ namespace MonoDevelop.CSharp.Formatting base.Dispose (); } - bool wasInVerbatimString; + bool? wasInVerbatimString; void HandleTextReplaced (object sender, DocumentChangeEventArgs e) { stateTracker.ResetEngineToPosition (e.Offset); + if (wasInVerbatimString == null) + return; if (e.RemovalLength != 1 || textEditorData.Document.CurrentAtomicUndoOperationType == OperationType.Format) return; SafeUpdateIndentEngine (Math.Min (textEditorData.Document.TextLength, e.Offset + e.InsertionLength + 1)); - if (wasInVerbatimString && !stateTracker.IsInsideVerbatimString) { + if (wasInVerbatimString == true && !stateTracker.IsInsideVerbatimString) { textEditorData.Document.TextReplacing -= HandleTextReplacing; textEditorData.Document.TextReplaced -= HandleTextReplaced; ConvertVerbatimStringToNormal (textEditorData, e.Offset + e.InsertionLength + 1); @@ -250,9 +235,9 @@ namespace MonoDevelop.CSharp.Formatting void HandleTextReplacing (object sender, DocumentChangeEventArgs e) { + wasInVerbatimString = null; var o = e.Offset + e.RemovalLength; if (o < 0 || o + 1 > textEditorData.Length || e.RemovalLength != 1 || textEditorData.Document.IsInUndo) { - wasInVerbatimString = false; return; } if (textEditorData.GetCharAt (o) != '"') @@ -294,14 +279,21 @@ namespace MonoDevelop.CSharp.Formatting var endOffset = offset; while (endOffset < textEditorData.Length) { char ch = textEditorData.GetCharAt (endOffset); - if (ch == '\\' && (endOffset + 1 < textEditorData.Length && textEditorData.GetCharAt (endOffset + 1) == '"')) { + if (ch == '\\') { + if (endOffset + 1 < textEditorData.Length && NewLine.IsNewLine (textEditorData.GetCharAt (endOffset + 1))) + return; + endOffset += 2; continue; } if (ch == '"') break; + if (NewLine.IsNewLine (ch)) + return; endOffset++; } + if (offset > endOffset || endOffset == textEditorData.Length) + return; var plainText = TextPasteUtils.StringLiteralPasteStrategy.Instance.Decode (textEditorData.GetTextAt (offset, endOffset - offset)); var newText = TextPasteUtils.VerbatimStringStrategy.Encode (plainText); textEditorData.Replace (offset, endOffset - offset, newText); @@ -316,11 +308,11 @@ namespace MonoDevelop.CSharp.Formatting endOffset += 2; continue; } - if (ch == '"') + if (ch == '"') { break; + } endOffset++; } - var plainText = TextPasteUtils.VerbatimStringStrategy.Decode (textEditorData.GetTextAt (offset, endOffset - offset)); var newText = TextPasteUtils.StringLiteralPasteStrategy.Instance.Encode (plainText); textEditorData.Replace (offset, endOffset - offset, newText); diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/CSharpSyntaxMode.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/CSharpSyntaxMode.cs index 73b8435615..4500ecd1d2 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/CSharpSyntaxMode.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Highlighting/CSharpSyntaxMode.cs @@ -128,7 +128,10 @@ namespace MonoDevelop.CSharp.Highlighting public static IEnumerable<string> GetDefinedSymbols (MonoDevelop.Projects.Project project) { - var configuration = project.GetConfiguration (IdeApp.Workspace.ActiveConfiguration) as DotNetProjectConfiguration; + var workspace = IdeApp.Workspace; + if (workspace == null) + yield break; + var configuration = project.GetConfiguration (workspace.ActiveConfiguration) as DotNetProjectConfiguration; if (configuration != null) { var cparams = configuration.CompilationParameters as CSharpCompilerParameters; if (cparams != null) { @@ -355,24 +358,26 @@ namespace MonoDevelop.CSharp.Highlighting static CSharpSyntaxMode () { MonoDevelop.Debugger.DebuggingService.DisableConditionalCompilation += DispatchService.GuiDispatch (new EventHandler<DocumentEventArgs> (OnDisableConditionalCompilation)); - IdeApp.Workspace.ActiveConfigurationChanged += delegate { - foreach (var doc in IdeApp.Workbench.Documents) { - TextEditorData data = doc.Editor; - if (data == null) - continue; - // Force syntax mode reparse (required for #if directives) - var editor = doc.Editor; - if (editor != null) { - if (data.Document.SyntaxMode is SyntaxMode) { - ((SyntaxMode)data.Document.SyntaxMode).UpdateDocumentHighlighting (); - SyntaxModeService.WaitUpdate (data.Document); + if (IdeApp.Workspace != null) { + IdeApp.Workspace.ActiveConfigurationChanged += delegate { + foreach (var doc in IdeApp.Workbench.Documents) { + TextEditorData data = doc.Editor; + if (data == null) + continue; + // Force syntax mode reparse (required for #if directives) + var editor = doc.Editor; + if (editor != null) { + if (data.Document.SyntaxMode is SyntaxMode) { + ((SyntaxMode)data.Document.SyntaxMode).UpdateDocumentHighlighting (); + SyntaxModeService.WaitUpdate (data.Document); + } + editor.Parent.TextViewMargin.PurgeLayoutCache (); + doc.ReparseDocument (); + editor.Parent.QueueDraw (); } - editor.Parent.TextViewMargin.PurgeLayoutCache (); - doc.ReparseDocument (); - editor.Parent.QueueDraw (); } - } - }; + }; + } CommentTag.SpecialCommentTagsChanged += (sender, e) => { UpdateCommentRule (); var actDoc = IdeApp.Workbench.ActiveDocument; diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringContext.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringContext.cs index 103fadae93..075eb6ca16 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringContext.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringContext.cs @@ -42,7 +42,7 @@ using MonoDevelop.CSharp.Formatting; namespace MonoDevelop.CSharp.Refactoring.CodeActions { - class MDRefactoringContext : RefactoringContext, IRefactoringContext + public class MDRefactoringContext : RefactoringContext, IRefactoringContext { public TextEditorData TextEditor { get; @@ -192,6 +192,7 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions this.location = loc; var policy = document.HasProject ? Project.Policies.Get<NameConventionPolicy> () : MonoDevelop.Projects.Policies.PolicyService.GetDefaultPolicy<NameConventionPolicy> (); Services.AddService (typeof(NamingConventionService), policy.CreateNRefactoryService ()); + Services.AddService (typeof(ICSharpCode.NRefactory.CSharp.CodeGenerationService), new CSharpCodeGenerationService()); } public MDRefactoringContext (DotNetProject project, TextEditorData data, ParsedDocument parsedDocument, CSharpAstResolver resolver, TextLocation loc, CancellationToken cancellationToken = default (CancellationToken)) : base (resolver, cancellationToken) diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringScript.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringScript.cs index 5a13b33e26..ce7035b512 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringScript.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeActions/MDRefactoringScript.cs @@ -99,7 +99,7 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions var declaringType = context.ParsedDocument.GetInnermostTypeDefinition (loc); var mode = new InsertionCursorEditMode ( editor.Parent, - CodeGenerationService.GetInsertionPoints (context.TextEditor, context.ParsedDocument, declaringType)); + MonoDevelop.Ide.TypeSystem.CodeGenerationService.GetInsertionPoints (context.TextEditor, context.ParsedDocument, declaringType)); if (mode.InsertionPoints.Count == 0) { MessageService.ShowError ( GettextCatalog.GetString ("No valid insertion point can be found in type '{0}'.", declaringType.Name) @@ -141,7 +141,7 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions iCArgs.InsertionPoint.LineAfter = NewLineInsertion.BlankLine; } foreach (var node in nodes.Reverse ()) { - var output = OutputNode (CodeGenerationService.CalculateBodyIndentLevel (declaringType), node); + var output = OutputNode (MonoDevelop.Ide.TypeSystem.CodeGenerationService.CalculateBodyIndentLevel (declaringType), node); var offset = context.TextEditor.LocationToOffset (iCArgs.InsertionPoint.Location); var delta = iCArgs.InsertionPoint.Insert (editor, output.Text); output.RegisterTrackedSegments (this, delta + offset); @@ -183,7 +183,7 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions var nodes = nodeCallback (script, script.context); var mode = new InsertionCursorEditMode ( editor.Parent, - CodeGenerationService.GetInsertionPoints (loadedDocument, declaringType)); + MonoDevelop.Ide.TypeSystem.CodeGenerationService.GetInsertionPoints (loadedDocument, declaringType)); if (mode.InsertionPoints.Count == 0) { MessageService.ShowError ( GettextCatalog.GetString ("No valid insertion point can be found in type '{0}'.", declaringType.Name) @@ -192,7 +192,7 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions } if (declaringType.Kind == TypeKind.Enum) { foreach (var node in nodes.Reverse ()) { - var output = OutputNode (CodeGenerationService.CalculateBodyIndentLevel (declaringType), node); + var output = OutputNode (MonoDevelop.Ide.TypeSystem.CodeGenerationService.CalculateBodyIndentLevel (declaringType), node); var point = mode.InsertionPoints.First (); var offset = loadedDocument.Editor.LocationToOffset (point.Location); var text = output.Text + ","; @@ -217,7 +217,7 @@ namespace MonoDevelop.CSharp.Refactoring.CodeActions iCArgs.InsertionPoint.LineAfter = NewLineInsertion.BlankLine; } foreach (var node in nodes.Reverse ()) { - var output = OutputNode (CodeGenerationService.CalculateBodyIndentLevel (declaringType), node); + var output = OutputNode (MonoDevelop.Ide.TypeSystem.CodeGenerationService.CalculateBodyIndentLevel (declaringType), node); var offset = loadedDocument.Editor.LocationToOffset (iCArgs.InsertionPoint.Location); var text = output.Text; var delta = iCArgs.InsertionPoint.Insert (editor, text); diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeIssues/Issues/MonoTODOIssue.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeIssues/Issues/MonoTODOIssue.cs new file mode 100644 index 0000000000..8236d7a5d3 --- /dev/null +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeIssues/Issues/MonoTODOIssue.cs @@ -0,0 +1,141 @@ +// +// MonoTODOIssue.cs +// +// Author: +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) +// +// 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 MonoDevelop.CSharp.Refactoring.CodeActions; +using MonoDevelop.CodeIssues; +using ICSharpCode.NRefactory.CSharp; +using System.Collections.Generic; +using ICSharpCode.NRefactory.Semantics; +using ICSharpCode.NRefactory.CSharp.Resolver; +using ICSharpCode.NRefactory.TypeSystem; +using System.Linq; + + +namespace MonoDevelop.CSharp.Refactoring.CodeIssues +{ + public class MonoTODOIssue : MonoDevelop.CodeIssues.CodeIssueProvider + { + public override bool HasSubIssues { + get { + return false; + } + } + + public MonoTODOIssue () + { + this.Title = "Mono TODO"; + this.Description = "Find usages of mono todo items"; + this.Category = IssueCategories.Notifications; + this.SetMimeType ("text/x-csharp"); + this.IsEnabledByDefault = true; + this.SetSeverity (ICSharpCode.NRefactory.Refactoring.Severity.Error); + this.SetIsEnabled (true); + } + + public override IEnumerable<CodeIssue> GetIssues (object refactoringContext, System.Threading.CancellationToken cancellationToken) + { + var context = refactoringContext as MDRefactoringContext; + if (context == null || context.IsInvalid || context.RootNode == null || context.ParsedDocument.HasErrors) + return new CodeIssue[0]; + var visitor = new MonoTODOVisitor (this, context); + context.RootNode.AcceptVisitor (visitor); + return visitor.Issues; + } + + class MonoTODOVisitor : DepthFirstAstVisitor + { + readonly MonoTODOIssue issue; + readonly MDRefactoringContext ctx; + public readonly List<CodeIssue> Issues = new List<CodeIssue> (); + + public MonoTODOVisitor (MonoTODOIssue issue, MDRefactoringContext ctx) + { + this.issue = issue; + this.ctx = ctx; + } + static readonly Dictionary<string, string> attributes = new Dictionary<string, string> { + { "MonoTODOAttribute", "Mono TODO" }, + { "MonoNotSupportedAttribute", "Mono NOT SUPPORTED" }, + { "MonoLimitationAttribute", "Mono LIMITATION" } + }; + void Check (AstNode node, IMember member) + { + foreach (var attr in member.Attributes) { + if (attr.AttributeType.Namespace != "System") + continue; + + string val; + if (attributes.TryGetValue (attr.AttributeType.Name, out val)) { + string msg = null; + var arg = attr.PositionalArguments.FirstOrDefault (); + if (arg != null) + msg = arg.ConstantValue != null ? arg.ConstantValue.ToString () : null; + Issues.Add (new CodeIssue (ICSharpCode.NRefactory.Refactoring.IssueMarker.WavedLine, + string.IsNullOrEmpty (msg) ? val : val + ": " + msg, + new DomRegion (node.StartLocation, node.EndLocation), + issue.IdString + )); + } + } + + } + + public override void VisitMemberReferenceExpression (MemberReferenceExpression memberReferenceExpression) + { + base.VisitMemberReferenceExpression (memberReferenceExpression); + var rr = ctx.Resolve (memberReferenceExpression) as MemberResolveResult; + if (rr == null || rr.IsError) + return; + Check (memberReferenceExpression, rr.Member); + } + + public override void VisitIdentifierExpression (IdentifierExpression identifierExpression) + { + base.VisitIdentifierExpression (identifierExpression); + var rr = ctx.Resolve (identifierExpression) as MemberResolveResult; + if (rr == null || rr.IsError) + return; + Check (identifierExpression, rr.Member); + } + + public override void VisitInvocationExpression (InvocationExpression invocationExpression) + { + base.VisitInvocationExpression (invocationExpression); + var rr = ctx.Resolve (invocationExpression) as CSharpInvocationResolveResult; + if (rr == null || rr.IsError) + return; + Check (invocationExpression, rr.Member); + } + + public override void VisitBlockStatement (BlockStatement blockStatement) + { + ctx.CancellationToken.ThrowIfCancellationRequested (); + base.VisitBlockStatement (blockStatement); + } + } + } +} + diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeIssues/NRefactoryIssueProvider.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeIssues/NRefactoryIssueProvider.cs index 633cdbeaae..25aa6b9767 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeIssues/NRefactoryIssueProvider.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring.CodeIssues/NRefactoryIssueProvider.cs @@ -43,7 +43,6 @@ namespace MonoDevelop.CSharp.Refactoring.CodeIssues readonly ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssueProvider issueProvider; readonly IssueDescriptionAttribute attr; readonly string providerIdString; - readonly ICSharpCode.NRefactory.CSharp.Refactoring.CodeActionProvider boundActionProvider; readonly TimerCounter counter; public override string IdString { @@ -90,14 +89,6 @@ namespace MonoDevelop.CSharp.Refactoring.CodeIssues SetMimeType ("text/x-csharp"); subIssues = issueProvider.SubIssues.Select (subIssue => (BaseCodeIssueProvider)new BaseNRefactoryIssueProvider (this, subIssue)).ToList (); - // Additional source of actions - var actionProvider = attr.ActionProvider; - if (actionProvider != null) { - var actionAttr = actionProvider.GetCustomAttributes (typeof(ContextActionAttribute), false); - if (actionAttr != null && actionAttr.Length == 1) - boundActionProvider = (ICSharpCode.NRefactory.CSharp.Refactoring.CodeActionProvider)Activator.CreateInstance (actionProvider); - } - counter = InstrumentationService.CreateTimerCounter (IdString, "CodeIssueProvider run times"); } @@ -118,17 +109,33 @@ namespace MonoDevelop.CSharp.Refactoring.CodeIssues return ToMonoDevelopRepresentation (cancellationToken, context, issues); } - IEnumerable<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction> GetActions (ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue issue, MDRefactoringContext context) + IEnumerable<NRefactoryCodeAction> GetActions (ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue issue, MDRefactoringContext context) { foreach (var action in issue.Actions) - yield return action; - if (boundActionProvider != null) { - // We need to se the correct location here. Seems very fragile to do so... - context.SetLocation (issue.Start); - foreach (var action in boundActionProvider.GetActions (context)) { - yield return action; + yield return new NRefactoryCodeAction (IdString, action.Description, action, action.SiblingKey); + + if (issue.ActionProvider != null) { + foreach (var provider in issue.ActionProvider) { + var boundActionProvider = (ICSharpCode.NRefactory.CSharp.Refactoring.CodeActionProvider)Activator.CreateInstance (provider); + context.SetLocation (issue.Start); + foreach (var action in boundActionProvider.GetActions (context)) { + yield return new NRefactoryCodeAction (provider.FullName, action.Description, action, action.SiblingKey); + } } } + /* + var nrefactoryCodeAction = new NRefactoryCodeAction (IdString, act.Description, act, act.SiblingKey); + if (act.SiblingKey != null) { + // make sure the action has a list of its siblings + IList<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction> siblingGroup; + if (!actionGroups.TryGetValue (act.SiblingKey, out siblingGroup)) { + siblingGroup = new List<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction> (); + actionGroups.Add (act.SiblingKey, siblingGroup); + } + siblingGroup.Add (act); + nrefactoryCodeAction.SiblingActions = siblingGroup; + } + */ } internal IEnumerable<CodeIssue> ToMonoDevelopRepresentation (CancellationToken cancellationToken, MDRefactoringContext context, IEnumerable<ICSharpCode.NRefactory.CSharp.Refactoring.CodeIssue> issues) @@ -142,43 +149,36 @@ namespace MonoDevelop.CSharp.Refactoring.CodeIssues continue; } var actions = new List<NRefactoryCodeAction> (); - foreach (var act in GetActions(issue, context)) { + foreach (var nrefactoryCodeAction in GetActions(issue, context)) { if (cancellationToken.IsCancellationRequested) yield break; - if (act == null) { + if (nrefactoryCodeAction == null) { LoggingService.LogError ("NRefactory issue action was null in :" + Title); continue; } - var nrefactoryCodeAction = new NRefactoryCodeAction (IdString, act.Description, act, act.SiblingKey); - if (act.SiblingKey != null) { - // make sure the action has a list of its siblings - IList<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction> siblingGroup; - if (!actionGroups.TryGetValue (act.SiblingKey, out siblingGroup)) { - siblingGroup = new List<ICSharpCode.NRefactory.CSharp.Refactoring.CodeAction> (); - actionGroups.Add (act.SiblingKey, siblingGroup); - } - siblingGroup.Add (act); - nrefactoryCodeAction.SiblingActions = siblingGroup; - } actions.Add (nrefactoryCodeAction); } - yield return new CodeIssue (issue.IssueMarker, GettextCatalog.GetString (issue.Description ?? ""), context.TextEditor.FileName, issue.Start, issue.End, IdString, actions); + yield return new CodeIssue (issue.IssueMarker, GettextCatalog.GetString (issue.Description ?? ""), context.TextEditor.FileName, issue.Start, issue.End, IdString, actions) { + ActionProvider = issue.ActionProvider + }; } } - public override bool CanDisableOnce { get { return !string.IsNullOrEmpty (attr.ResharperDisableKeyword); } } + public override bool CanDisableOnce { get { return !string.IsNullOrEmpty (attr.AnalysisDisableKeyword); } } - public override bool CanDisableAndRestore { get { return !string.IsNullOrEmpty (attr.ResharperDisableKeyword); } } + public override bool CanDisableAndRestore { get { return !string.IsNullOrEmpty (attr.AnalysisDisableKeyword); } } public override bool CanDisableWithPragma { get { return attr.PragmaWarning > 0; } } public override bool CanSuppressWithAttribute { get { return !string.IsNullOrEmpty (attr.SuppressMessageCheckId); } } + const string analysisDisableTag = "Analysis "; + public override void DisableOnce (MonoDevelop.Ide.Gui.Document document, DocumentRegion loc) { document.Editor.Insert ( document.Editor.LocationToOffset (loc.BeginLine, 1), - document.Editor.IndentationTracker.GetIndentationString (loc.Begin) + "// ReSharper disable once " + attr.ResharperDisableKeyword + document.Editor.EolMarker + document.Editor.IndentationTracker.GetIndentationString (loc.Begin) + "// " + analysisDisableTag + "disable once " + attr.AnalysisDisableKeyword + document.Editor.EolMarker ); } @@ -187,11 +187,11 @@ namespace MonoDevelop.CSharp.Refactoring.CodeIssues using (document.Editor.OpenUndoGroup ()) { document.Editor.Insert ( document.Editor.LocationToOffset (loc.EndLine + 1, 1), - document.Editor.IndentationTracker.GetIndentationString (loc.End) + "// ReSharper restore " + attr.ResharperDisableKeyword + document.Editor.EolMarker + document.Editor.IndentationTracker.GetIndentationString (loc.End) + "// " + analysisDisableTag + "restore " + attr.AnalysisDisableKeyword + document.Editor.EolMarker ); document.Editor.Insert ( document.Editor.LocationToOffset (loc.BeginLine, 1), - document.Editor.IndentationTracker.GetIndentationString (loc.Begin) + "// ReSharper disable " + attr.ResharperDisableKeyword + document.Editor.EolMarker + document.Editor.IndentationTracker.GetIndentationString (loc.Begin) + "// " + analysisDisableTag + "disable " + attr.AnalysisDisableKeyword + document.Editor.EolMarker ); } } diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerationService.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerationService.cs new file mode 100644 index 0000000000..52bd152f07 --- /dev/null +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerationService.cs @@ -0,0 +1,61 @@ +// +// CSharpCodeGenerationService.cs +// +// Author: +// Mike Krüger <mkrueger@xamarin.com> +// +// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) +// +// 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 ICSharpCode.NRefactory.CSharp; +using ICSharpCode.NRefactory.TypeSystem; +using ICSharpCode.NRefactory.CSharp.Refactoring; +using System.Linq; + +namespace MonoDevelop.CSharp.Refactoring +{ + public class CSharpCodeGenerationService : DefaultCodeGenerationService + { + public override EntityDeclaration GenerateMemberImplementation (RefactoringContext context, IMember member, bool explicitImplementation) + { + var result = base.GenerateMemberImplementation (context, member, explicitImplementation); + if (CSharpCodeGenerator.IsMonoTouchModelMember (member)) { + var m = result as MethodDeclaration; + if (m != null) { + for (int i = CSharpCodeGenerator.MonoTouchComments.Length - 1; i >= 0; i--) { + m.Body.InsertChildBefore (m.Body.Statements.First (), new Comment (CSharpCodeGenerator.MonoTouchComments [i]), Roles.Comment); + } + } + + var p = result as PropertyDeclaration; + if (p != null) { + for (int i = CSharpCodeGenerator.MonoTouchComments.Length - 1; i >= 0; i--) { + if (!p.Getter.IsNull) + p.Getter.Body.InsertChildBefore (p.Getter.Body.Statements.First (), new Comment (CSharpCodeGenerator.MonoTouchComments [i]), Roles.Comment); + if (!p.Setter.IsNull) + p.Setter.Body.InsertChildBefore (p.Setter.Body.Statements.First (), new Comment (CSharpCodeGenerator.MonoTouchComments [i]), Roles.Comment); + } + } + } + return result; + } + } +} + diff --git a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerator.cs b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerator.cs index 2465fe4316..b72fca3c5e 100644 --- a/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerator.cs +++ b/main/src/addins/CSharpBinding/MonoDevelop.CSharp.Refactoring/CSharpCodeGenerator.cs @@ -379,17 +379,20 @@ namespace MonoDevelop.CSharp.Refactoring bodyEndOffset = result.Length; AppendLine (result); } - + + internal static string[] MonoTouchComments = { + " NOTE: Don't call the base implementation on a Model class", + " see http://docs.xamarin.com/guides/ios/application_fundamentals/delegates,_protocols,_and_events" + }; + void AppendMonoTouchTodo (StringBuilder result, CodeGenerationOptions options, out int bodyStartOffset, out int bodyEndOffset) { AppendIndent (result); bodyStartOffset = result.Length; - result.AppendLine ("// NOTE: Don't call the base implementation on a Model class"); - - AppendIndent (result); - result.AppendLine ("// see http://docs.xamarin.com/guides/ios/application_fundamentals/delegates,_protocols,_and_events "); - - AppendIndent (result); + foreach (var cmt in MonoTouchComments) { + result.AppendLine ("//" + cmt); + AppendIndent (result); + } result.Append ("throw new "); result.Append (options.GetShortType ("System", "NotImplementedException")); @@ -809,7 +812,7 @@ namespace MonoDevelop.CSharp.Refactoring return new CodeGeneratorMemberResult (result.ToString (), regions); } - static bool IsMonoTouchModelMember (IMember member) + internal static bool IsMonoTouchModelMember (IMember member) { if (member == null || member.DeclaringType == null) return false; diff --git a/main/src/addins/MacPlatform/MacInterop/Keychain.cs b/main/src/addins/MacPlatform/MacInterop/Keychain.cs index fb5fafe516..bd6ef514fa 100644 --- a/main/src/addins/MacPlatform/MacInterop/Keychain.cs +++ b/main/src/addins/MacPlatform/MacInterop/Keychain.cs @@ -698,7 +698,8 @@ namespace MonoDevelop.MacInterop public static unsafe void AddInternetPassword (Uri uri, string username, string password) { - byte[] path = Encoding.UTF8.GetBytes (string.Join (string.Empty, uri.Segments).Substring (1)); // don't include the leading '/' + var pathStr = string.Join (string.Empty, uri.Segments); + byte[] path = pathStr.Length > 0 ? Encoding.UTF8.GetBytes (pathStr.Substring (1)) : new byte[0]; // don't include the leading '/' byte[] passwd = Encoding.UTF8.GetBytes (password); byte[] host = Encoding.UTF8.GetBytes (uri.Host); byte[] user = Encoding.UTF8.GetBytes (username); @@ -736,7 +737,8 @@ namespace MonoDevelop.MacInterop public static unsafe void AddInternetPassword (Uri uri, string password) { - byte[] path = Encoding.UTF8.GetBytes (string.Join (string.Empty, uri.Segments).Substring (1)); // don't include the leading '/' + var pathStr = string.Join (string.Empty, uri.Segments); + byte[] path = pathStr.Length > 0 ? Encoding.UTF8.GetBytes (pathStr.Substring (1)) : new byte[0]; // don't include the leading '/' byte[] user = Encoding.UTF8.GetBytes (Uri.UnescapeDataString (uri.UserInfo)); byte[] passwd = Encoding.UTF8.GetBytes (password); byte[] host = Encoding.UTF8.GetBytes (uri.Host); @@ -806,7 +808,8 @@ namespace MonoDevelop.MacInterop public static unsafe Tuple<string, string> FindInternetUserNameAndPassword (Uri uri) { - byte[] path = Encoding.UTF8.GetBytes (string.Join (string.Empty, uri.Segments).Substring (1)); // don't include the leading '/' + var pathStr = string.Join (string.Empty, uri.Segments); + byte[] path = pathStr.Length > 0 ? Encoding.UTF8.GetBytes (pathStr.Substring (1)) : new byte[0]; // don't include the leading '/' byte[] host = Encoding.UTF8.GetBytes (uri.Host); var auth = GetSecAuthenticationType (uri.Query); var protocol = GetSecProtocolType (uri.Scheme); @@ -831,7 +834,8 @@ namespace MonoDevelop.MacInterop public static string FindInternetPassword (Uri uri) { - byte[] path = Encoding.UTF8.GetBytes (string.Join (string.Empty, uri.Segments).Substring (1)); // don't include the leading '/' + var pathStr = string.Join (string.Empty, uri.Segments); + byte[] path = pathStr.Length > 0 ? Encoding.UTF8.GetBytes (pathStr.Substring (1)) : new byte[0]; // don't include the leading '/' byte[] user = Encoding.UTF8.GetBytes (Uri.UnescapeDataString (uri.UserInfo)); byte[] host = Encoding.UTF8.GetBytes (uri.Host); var auth = GetSecAuthenticationType (uri.Query); diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/CorApi2/Metadata/CorMetadata.cs b/main/src/addins/MonoDevelop.Debugger.Win32/CorApi2/Metadata/CorMetadata.cs index 4b1920c594..cc0fc283bd 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/CorApi2/Metadata/CorMetadata.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/CorApi2/Metadata/CorMetadata.cs @@ -598,7 +598,15 @@ namespace Microsoft.Samples.Debugging.CorMetadata public static void ReadMethodSignature (IMetadataImport importer, ref IntPtr pData, out CorCallingConvention cconv, out Type retType, out List<Type> argTypes)
{
cconv = MetadataHelperFunctions.CorSigUncompressCallingConv (ref pData);
- uint numArgs = MetadataHelperFunctions.CorSigUncompressData (ref pData);
+ uint numArgs = 0;
+ // FIXME: Use number of <T>s.
+ uint types = 0;
+ if ((cconv & CorCallingConvention.Generic) == CorCallingConvention.Generic)
+ types = MetadataHelperFunctions.CorSigUncompressData (ref pData);
+
+ if (cconv != CorCallingConvention.Field)
+ numArgs = MetadataHelperFunctions.CorSigUncompressData (ref pData);
+
retType = MetadataHelperFunctions.ReadType (importer, ref pData);
argTypes = new List<Type> ();
for (int n = 0; n < numArgs; n++)
@@ -667,6 +675,7 @@ namespace Microsoft.Samples.Debugging.CorMetadata return MetadataType.MakeByRef(t);
}
+ case CorElementType.ELEMENT_TYPE_END:
case CorElementType.ELEMENT_TYPE_VALUETYPE:
case CorElementType.ELEMENT_TYPE_CLASS: {
uint token = CorSigUncompressToken (ref pData);
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/CorApi2/Metadata/MetadataFieldInfo.cs b/main/src/addins/MonoDevelop.Debugger.Win32/CorApi2/Metadata/MetadataFieldInfo.cs index 262979bba2..360d83acd4 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/CorApi2/Metadata/MetadataFieldInfo.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/CorApi2/Metadata/MetadataFieldInfo.cs @@ -76,7 +76,7 @@ namespace Microsoft.Samples.Debugging.CorMetadata Debug.Assert(callingConv == CorCallingConvention.Field);
CorElementType elementType = MetadataHelperFunctions.CorSigUncompressElementType(ref ppvSigTemp);
- if (elementType == CorElementType.ELEMENT_TYPE_VALUETYPE)
+ if (elementType == CorElementType.ELEMENT_TYPE_END || elementType == CorElementType.ELEMENT_TYPE_VALUETYPE)
{
uint token = MetadataHelperFunctions.CorSigUncompressToken(ref ppvSigTemp);
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/ArrayAdaptor.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/ArrayAdaptor.cs index 0f2dfe3c9f..78e7acbdd4 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/ArrayAdaptor.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/ArrayAdaptor.cs @@ -25,8 +25,6 @@ // // -using System; -using Mono.Debugging.Client; using Microsoft.Samples.Debugging.CorDebug; using Mono.Debugging.Evaluation; @@ -34,9 +32,9 @@ namespace MonoDevelop.Debugger.Win32 { class ArrayAdaptor: ICollectionAdaptor { - CorEvaluationContext ctx; + readonly CorEvaluationContext ctx; CorArrayValue array; - CorValRef obj; + readonly CorValRef obj; public ArrayAdaptor (EvaluationContext ctx, CorValRef obj, CorArrayValue array) { @@ -47,19 +45,19 @@ namespace MonoDevelop.Debugger.Win32 public int[] GetDimensions () { - if (array != null) - return array.GetDimensions (); - else - return new int[0]; + return array != null ? array.GetDimensions () : new int[0]; } public object GetElement (int[] indices) { return new CorValRef (delegate { - if (array != null) - return array.GetElement (indices); - else - return null; + // If we have a zombie state array, reload it. + if (!obj.IsValid) { + obj.Reload (); + array = CorObjectAdaptor.GetRealObject (ctx, obj) as CorArrayValue; + } + + return array != null ? array.GetElement (indices) : null; }); } diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorBacktrace.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorBacktrace.cs index b8131a61cb..9807a3738f 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorBacktrace.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorBacktrace.cs @@ -1,14 +1,10 @@ -using System;
-using System.Reflection;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using System.Collections.Generic;
using System.Diagnostics.SymbolStore;
-using Mono.Debugging.Client;
-using Mono.Debugging.Backend;
+using System.Reflection;
using Microsoft.Samples.Debugging.CorDebug;
using Microsoft.Samples.Debugging.CorDebug.NativeApi;
using Microsoft.Samples.Debugging.CorMetadata;
+using Mono.Debugging.Client;
using Mono.Debugging.Evaluation;
namespace MonoDevelop.Debugger.Win32
@@ -16,8 +12,8 @@ namespace MonoDevelop.Debugger.Win32 class CorBacktrace: BaseBacktrace
{
CorThread thread;
- int threadId;
- CorDebuggerSession session;
+ readonly int threadId;
+ readonly CorDebuggerSession session;
List<CorFrame> frames;
int evalTimestamp;
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorDebuggerEngine.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorDebuggerEngine.cs index ef754137f2..5f03f31278 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorDebuggerEngine.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorDebuggerEngine.cs @@ -1,13 +1,10 @@ using System;
using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using MonoDevelop.Core.Execution;
-using MonoDevelop.Core.Assemblies;
+using System.IO;
using Mono.Debugging.Client;
using MonoDevelop.AspNet;
using MonoDevelop.Core;
-using System.IO;
+using MonoDevelop.Core.Execution;
namespace MonoDevelop.Debugger.Win32
{
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorDebuggerSession.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorDebuggerSession.cs index eba9af95a2..3484a1ee90 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorDebuggerSession.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorDebuggerSession.cs @@ -1,26 +1,25 @@ using System;
-using System.Threading;
-using System.Text;
using System.Collections;
using System.Collections.Generic;
-using System.Linq;
-using Mono.Debugging.Client;
-using Mono.Debugging.Backend;
-using System.Runtime.InteropServices;
using System.Diagnostics.SymbolStore;
+using System.Reflection;
+using System.Runtime.InteropServices;
+using System.Text;
+using System.Threading;
using Microsoft.Samples.Debugging.CorDebug;
+using Microsoft.Samples.Debugging.CorDebug.NativeApi;
using Microsoft.Samples.Debugging.CorMetadata;
using Microsoft.Samples.Debugging.CorSymbolStore;
-using Microsoft.Samples.Debugging.CorDebug.NativeApi;
+using Mono.Debugging.Backend;
+using Mono.Debugging.Client;
using Mono.Debugging.Evaluation;
-using System.Reflection;
namespace MonoDevelop.Debugger.Win32
{
public class CorDebuggerSession: DebuggerSession
{
- object debugLock = new object ();
- object terminateLock = new object ();
+ readonly object debugLock = new object ();
+ readonly object terminateLock = new object ();
CorDebugger dbg;
CorProcess process;
@@ -32,13 +31,13 @@ namespace MonoDevelop.Debugger.Win32 static int evaluationTimestamp;
- SymbolBinder symbolBinder = new SymbolBinder ();
+ readonly SymbolBinder symbolBinder = new SymbolBinder ();
Dictionary<string, DocInfo> documents;
Dictionary<int, ProcessInfo> processes = new Dictionary<int, ProcessInfo> ();
Dictionary<int, ThreadInfo> threads = new Dictionary<int,ThreadInfo> ();
Dictionary<string, ModuleInfo> modules;
- Dictionary<CorBreakpoint, BreakEventInfo> breakpoints = new Dictionary<CorBreakpoint, BreakEventInfo> ();
- Dictionary<long, CorHandleValue> handles = new Dictionary<long, CorHandleValue>();
+ readonly Dictionary<CorBreakpoint, BreakEventInfo> breakpoints = new Dictionary<CorBreakpoint, BreakEventInfo> ();
+ readonly Dictionary<long, CorHandleValue> handles = new Dictionary<long, CorHandleValue>();
public CorObjectAdaptor ObjectAdapter;
@@ -143,7 +142,7 @@ namespace MonoDevelop.Debugger.Win32 int flags = 0;
if (!startInfo.UseExternalConsole) {
- flags = 0x08000000; /* CREATE_NO_WINDOW*/
+ flags = (int)CreationFlags.CREATE_NO_WINDOW;
flags |= CorDebugger.CREATE_REDIRECT_STD;
}
@@ -581,7 +580,7 @@ namespace MonoDevelop.Debugger.Win32 return MtaThread.Run (() => new ProcessInfo[] { GetProcess (process) });
}
- protected override Mono.Debugging.Client.Backtrace OnGetThreadBacktrace (long processId, long threadId)
+ protected override Backtrace OnGetThreadBacktrace (long processId, long threadId)
{
return MtaThread.Run (delegate
{
@@ -913,7 +912,7 @@ namespace MonoDevelop.Debugger.Win32 eval.Abort ();
};
mc.OnGetDescription = delegate {
- System.Reflection.MethodInfo met = function.GetMethodInfo (ctx.Session);
+ MethodInfo met = function.GetMethodInfo (ctx.Session);
if (met != null)
return met.Name;
else
@@ -1131,7 +1130,7 @@ namespace MonoDevelop.Debugger.Win32 {
Type classType = val.ExactType.GetTypeInfo (this);
// Loop through all private instance fields in the thread class
- foreach (MetadataFieldInfo fi in classType.GetFields (BindingFlags.NonPublic | BindingFlags.Instance))
+ foreach (FieldInfo fi in classType.GetFields (BindingFlags.NonPublic | BindingFlags.Instance))
{
if (fi.Name == "m_Name")
{
@@ -1290,7 +1289,7 @@ namespace MonoDevelop.Debugger.Win32 return reader.GetMethod (new SymbolToken (func.Token));
}
- public static System.Reflection.MethodInfo GetMethodInfo (this CorFunction func, CorDebuggerSession session)
+ public static MethodInfo GetMethodInfo (this CorFunction func, CorDebuggerSession session)
{
CorMetadataImport mi = session.GetMetadataForModule (func.Module.Name);
if (mi != null)
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorEvaluationContext.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorEvaluationContext.cs index e6dd5352ea..1435fe4ef7 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorEvaluationContext.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorEvaluationContext.cs @@ -1,10 +1,7 @@ using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Mono.Debugging.Evaluation;
-using DC=Mono.Debugging.Client;
using Microsoft.Samples.Debugging.CorDebug;
+using Mono.Debugging.Evaluation;
+using DC = Mono.Debugging.Client;
namespace MonoDevelop.Debugger.Win32
{
@@ -14,7 +11,7 @@ namespace MonoDevelop.Debugger.Win32 CorFrame frame;
int frameIndex;
int evalTimestamp;
- CorBacktrace backtrace;
+ readonly CorBacktrace backtrace;
CorThread thread;
int threadId;
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorMethodCall.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorMethodCall.cs index b0ef074db7..1d8ea6777c 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorMethodCall.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorMethodCall.cs @@ -1,8 +1,4 @@ -using System;
-using System.Threading;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
+using System.Threading;
using Mono.Debugging.Evaluation;
namespace MonoDevelop.Debugger.Win32
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorObjectAdaptor.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorObjectAdaptor.cs index 8b82d44aee..4df85f5d4b 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorObjectAdaptor.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorObjectAdaptor.cs @@ -27,21 +27,21 @@ using System;
using System.Collections;
-using System.Reflection;
using System.Collections.Generic;
-using System.Text;
using System.Diagnostics;
-using SR = System.Reflection;
-using Mono.Debugging.Client;
-using Mono.Debugging.Backend;
-using Microsoft.Samples.Debugging.CorDebug;
-using Mono.Debugging.Evaluation;
-using CorElementType = Microsoft.Samples.Debugging.CorDebug.NativeApi.CorElementType;
-using CorDebugMappingResult = Microsoft.Samples.Debugging.CorDebug.NativeApi.CorDebugMappingResult;
-using CorDebugHandleType = Microsoft.Samples.Debugging.CorDebug.NativeApi.CorDebugHandleType;
using System.Diagnostics.SymbolStore;
+using System.Reflection;
+using System.Text;
+using Microsoft.Samples.Debugging.CorDebug;
using Microsoft.Samples.Debugging.CorMetadata;
+using Mono.Debugging.Backend;
+using Mono.Debugging.Client;
+using Mono.Debugging.Evaluation;
using MonoDevelop.Core.Collections;
+using SR = System.Reflection;
+using CorDebugHandleType = Microsoft.Samples.Debugging.CorDebug.NativeApi.CorDebugHandleType;
+using CorDebugMappingResult = Microsoft.Samples.Debugging.CorDebug.NativeApi.CorDebugMappingResult;
+using CorElementType = Microsoft.Samples.Debugging.CorDebug.NativeApi.CorElementType;
namespace MonoDevelop.Debugger.Win32
{
@@ -55,8 +55,8 @@ namespace MonoDevelop.Debugger.Win32 public override bool IsPointer (EvaluationContext ctx, object val)
{
- // FIXME: implement this correctly.
- return false;
+ CorType type = (CorType) GetValueType (ctx, val);
+ return IsPointer (type);
}
public override bool IsEnum (EvaluationContext ctx, object val)
@@ -167,7 +167,7 @@ namespace MonoDevelop.Debugger.Win32 return null;
}
- T[] CastArray<T> (object[] array)
+ static T[] CastArray<T> (object[] array)
{
if (array == null)
return null;
@@ -284,7 +284,7 @@ namespace MonoDevelop.Debugger.Win32 return val;
}
- bool IsValueType (CorEvaluationContext ctx, CorValRef val)
+ static bool IsValueType (CorEvaluationContext ctx, CorValRef val)
{
CorValue v = GetRealObject (ctx, val);
if (v.Type == CorElementType.ELEMENT_TYPE_VALUETYPE)
@@ -497,7 +497,7 @@ namespace MonoDevelop.Debugger.Win32 foreach (Type t in GetAllTypes (ctx)) {
if (t.Namespace == namspace)
types.Add (t.FullName);
- else if (t.Namespace.StartsWith (namspace + ".")) {
+ else if (t.Namespace.StartsWith (namspace + ".", StringComparison.Ordinal)) {
if (t.Namespace.IndexOf ('.', namspace.Length + 1) == -1)
nss.Add (t.Namespace);
}
@@ -591,6 +591,11 @@ namespace MonoDevelop.Debugger.Win32 return null;
}
+ public bool IsPointer (CorType targetType)
+ {
+ return targetType.Type == CorElementType.ELEMENT_TYPE_PTR;
+ }
+
public object CreateEnum (EvaluationContext ctx, CorType type, object val)
{
object systemEnumType = GetType (ctx, "System.Enum");
@@ -939,7 +944,6 @@ namespace MonoDevelop.Debugger.Win32 if (arr != null)
return base.TargetObjectToObject(ctx, objr);
- CorEvaluationContext cctx = (CorEvaluationContext) ctx;
CorObjectValue co = obj as CorObjectValue;
if (co != null)
return base.TargetObjectToObject(ctx, objr);
@@ -1067,7 +1071,7 @@ namespace MonoDevelop.Debugger.Win32 foreach (ISymbolScope cs in scope.GetChildren ()) {
if (cs.StartOffset <= offset && cs.EndOffset >= offset) {
- foreach (VariableReference var in GetLocals (ctx, cs, offset, showHidden))
+ foreach (ValueReference var in GetLocals (ctx, cs, offset, showHidden))
yield return var;
}
}
@@ -1082,6 +1086,8 @@ namespace MonoDevelop.Debugger.Win32 if (t == null)
return null;
+ // FIXME: find out how to implement CompilerGenerated.
+ //bool isCompilerGenerated = false;
string proxyType = null;
string nameDisplayString = null;
string typeDisplayString = null;
@@ -1089,39 +1095,43 @@ namespace MonoDevelop.Debugger.Win32 Dictionary<string, DebuggerBrowsableState> memberData = null;
bool hasTypeData = false;
- foreach (object att in t.GetCustomAttributes (false)) {
- DebuggerTypeProxyAttribute patt = att as DebuggerTypeProxyAttribute;
- if (patt != null) {
- proxyType = patt.ProxyTypeName;
- hasTypeData = true;
- continue;
- }
- DebuggerDisplayAttribute datt = att as DebuggerDisplayAttribute;
- if (datt != null) {
- hasTypeData = true;
- nameDisplayString = datt.Name;
- typeDisplayString = datt.Type;
- valueDisplayString = datt.Value;
- continue;
+ try {
+ foreach (object att in t.GetCustomAttributes (false)) {
+ DebuggerTypeProxyAttribute patt = att as DebuggerTypeProxyAttribute;
+ if (patt != null) {
+ proxyType = patt.ProxyTypeName;
+ hasTypeData = true;
+ continue;
+ }
+ DebuggerDisplayAttribute datt = att as DebuggerDisplayAttribute;
+ if (datt != null) {
+ hasTypeData = true;
+ nameDisplayString = datt.Name;
+ typeDisplayString = datt.Type;
+ valueDisplayString = datt.Value;
+ continue;
+ }
}
- }
- ArrayList mems = new ArrayList ();
- mems.AddRange (t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance));
- mems.AddRange (t.GetProperties (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance));
+ ArrayList mems = new ArrayList ();
+ mems.AddRange (t.GetFields (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance));
+ mems.AddRange (t.GetProperties (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance));
- foreach (MemberInfo m in mems) {
- object[] atts = m.GetCustomAttributes (typeof (DebuggerBrowsableAttribute), false);
- if (atts.Length == 0) {
- atts = m.GetCustomAttributes (typeof (System.Runtime.CompilerServices.CompilerGeneratedAttribute), false);
- if (atts.Length > 0)
- atts[0] = new DebuggerBrowsableAttribute (DebuggerBrowsableState.Never);
- }
- if (atts.Length > 0) {
- hasTypeData = true;
- if (memberData == null) memberData = new Dictionary<string, DebuggerBrowsableState> ();
- memberData[m.Name] = ((DebuggerBrowsableAttribute)atts[0]).State;
+ foreach (MemberInfo m in mems) {
+ object[] atts = m.GetCustomAttributes (typeof (DebuggerBrowsableAttribute), false);
+ if (atts.Length == 0) {
+ atts = m.GetCustomAttributes (typeof (System.Runtime.CompilerServices.CompilerGeneratedAttribute), false);
+ if (atts.Length > 0)
+ atts[0] = new DebuggerBrowsableAttribute (DebuggerBrowsableState.Never);
+ }
+ if (atts.Length > 0) {
+ hasTypeData = true;
+ if (memberData == null) memberData = new Dictionary<string, DebuggerBrowsableState> ();
+ memberData[m.Name] = ((DebuggerBrowsableAttribute)atts[0]).State;
+ }
}
+ } catch (Exception ex) {
+ ctx.WriteDebuggerError (ex);
}
if (hasTypeData)
return new TypeDisplayData (proxyType, valueDisplayString, typeDisplayString, nameDisplayString, false, memberData);
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorValRef.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorValRef.cs index 4e836921b5..71ec9e1a07 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorValRef.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/CorValRef.cs @@ -1,17 +1,11 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Microsoft.Samples.Debugging.CorDebug;
-using Mono.Debugging.Evaluation;
-using Mono.Debugging.Client;
+using Microsoft.Samples.Debugging.CorDebug;
namespace MonoDevelop.Debugger.Win32
{
public class CorValRef
{
CorValue val;
- ValueLoader loader;
+ readonly ValueLoader loader;
int version;
public delegate CorValue ValueLoader ( );
@@ -46,14 +40,21 @@ namespace MonoDevelop.Debugger.Win32 }
}
+ public void Reload ()
+ {
+ if (loader != null) {
+ // Obsolete value, get a new one
+ CorValue v = loader ();
+ version = CorDebuggerSession.EvaluationTimestamp;
+ if (v != null)
+ val = v;
+ }
+ }
+
public CorValue Val {
get {
- if (version < CorDebuggerSession.EvaluationTimestamp && loader != null) {
- // Obsolete value, get a new one
- CorValue v = loader ();
- version = CorDebuggerSession.EvaluationTimestamp;
- if (v != null)
- val = v;
+ if (version < CorDebuggerSession.EvaluationTimestamp) {
+ Reload ();
}
return val;
}
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/FieldReference.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/FieldReference.cs index 243400ccb4..8043c83287 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/FieldReference.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/FieldReference.cs @@ -25,20 +25,19 @@ // // -using System; using System.Reflection; +using Microsoft.Samples.Debugging.CorDebug; using Mono.Debugging.Client; using Mono.Debugging.Evaluation; -using Microsoft.Samples.Debugging.CorDebug; namespace MonoDevelop.Debugger.Win32 { public class FieldReference: ValueReference { - CorType type; - FieldInfo field; - CorValRef thisobj; - CorValRef.ValueLoader loader; + readonly CorType type; + readonly FieldInfo field; + readonly CorValRef thisobj; + readonly CorValRef.ValueLoader loader; public FieldReference (EvaluationContext ctx, CorValRef thisobj, CorType type, FieldInfo field) : base (ctx) @@ -70,8 +69,7 @@ namespace MonoDevelop.Debugger.Win32 get { if (field.IsLiteral && field.IsStatic) return field.GetValue (null); - else - return base.ObjectValue; + return base.ObjectValue; } } @@ -86,7 +84,7 @@ namespace MonoDevelop.Debugger.Win32 else { if (field.IsLiteral && field.IsStatic) { object oval = field.GetValue (null); - CorObjectAdaptor ad = (CorObjectAdaptor)ctx.Adapter; + CorObjectAdaptor ad = ctx.Adapter; // When getting enum members, convert the integer value to an enum value if (ad.IsEnum (ctx, type)) return ad.CreateEnum (ctx, type, Context.Adapter.CreateValue (ctx, oval)); diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaBacktrace.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaBacktrace.cs index cf0da776a7..f20e0bc3a8 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaBacktrace.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaBacktrace.cs @@ -1,15 +1,11 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Mono.Debugging.Backend;
+using Mono.Debugging.Backend;
using Mono.Debugging.Client;
namespace MonoDevelop.Debugger.Win32
{
class MtaBacktrace: IBacktrace
{
- IBacktrace backtrace;
+ readonly IBacktrace backtrace;
public MtaBacktrace (IBacktrace bt)
{
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaObjectValueSource.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaObjectValueSource.cs index c87fa6f38b..8e35308164 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaObjectValueSource.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaObjectValueSource.cs @@ -1,15 +1,11 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Mono.Debugging.Backend;
+using Mono.Debugging.Backend;
using Mono.Debugging.Client;
namespace MonoDevelop.Debugger.Win32
{
class MtaObjectValueSource: IObjectValueSource
{
- IObjectValueSource source;
+ readonly IObjectValueSource source;
public MtaObjectValueSource (IObjectValueSource s)
{
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaObjectValueUpdater.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaObjectValueUpdater.cs index 6f8cf92350..a6b5f4a10f 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaObjectValueUpdater.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaObjectValueUpdater.cs @@ -1,15 +1,10 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Mono.Debugging.Backend;
-using Mono.Debugging.Client;
+using Mono.Debugging.Backend;
namespace MonoDevelop.Debugger.Win32
{
class MtaObjectValueUpdater : IObjectValueUpdater
{
- IObjectValueUpdater source;
+ readonly IObjectValueUpdater source;
public MtaObjectValueUpdater (IObjectValueUpdater s)
{
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValue.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValue.cs index b2d6eda7f0..f2511819e4 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValue.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValue.cs @@ -1,15 +1,11 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Mono.Debugging.Backend;
+using Mono.Debugging.Backend;
using Mono.Debugging.Client;
namespace MonoDevelop.Debugger.Win32
{
class MtaRawValue : IRawValue
{
- IRawValue source;
+ readonly IRawValue source;
public MtaRawValue (IRawValue s)
{
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValueArray.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValueArray.cs index bd7300ea87..2e92af3087 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValueArray.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValueArray.cs @@ -1,15 +1,11 @@ using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
using Mono.Debugging.Backend;
-using Mono.Debugging.Client;
namespace MonoDevelop.Debugger.Win32
{
class MtaRawValueArray : IRawValueArray
{
- IRawValueArray source;
+ readonly IRawValueArray source;
public MtaRawValueArray (IRawValueArray s)
{
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValueString.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValueString.cs index 93a8821cff..245a455be2 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValueString.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaRawValueString.cs @@ -1,15 +1,10 @@ -using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
-using Mono.Debugging.Backend;
-using Mono.Debugging.Client;
+using Mono.Debugging.Backend;
namespace MonoDevelop.Debugger.Win32
{
class MtaRawValueString : IRawValueString
{
- IRawValueString source;
+ readonly IRawValueString source;
public MtaRawValueString (IRawValueString s)
{
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaThread.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaThread.cs index 036080c40d..d46b7aca0b 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaThread.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/MtaThread.cs @@ -1,19 +1,16 @@ using System;
-using System.Collections.Generic;
-using System.Linq;
-using System.Text;
using System.Threading;
namespace MonoDevelop.Debugger.Win32
{
- class MtaThread
+ static class MtaThread
{
- static AutoResetEvent wordDoneEvent = new AutoResetEvent (false);
+ static readonly AutoResetEvent wordDoneEvent = new AutoResetEvent (false);
static Action workDelegate;
- static object workLock = new object ();
+ static readonly object workLock = new object ();
static Thread workThread;
static Exception workError;
- static object threadLock = new object ();
+ static readonly object threadLock = new object ();
public static R Run<R> (Func<R> ts)
{
diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/PropertyReference.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/PropertyReference.cs index 9c31bac3b9..1d1dfa3cb9 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/PropertyReference.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/PropertyReference.cs @@ -25,7 +25,6 @@ // // -using System; using System.Reflection; using Mono.Debugging.Client; using Mono.Debugging.Evaluation; @@ -35,12 +34,12 @@ namespace MonoDevelop.Debugger.Win32 { class PropertyReference: ValueReference { - PropertyInfo prop; - CorValRef thisobj; - CorValRef[] index; - CorModule module; - CorType declaringType; - CorValRef.ValueLoader loader; + readonly PropertyInfo prop; + readonly CorValRef thisobj; + readonly CorValRef[] index; + readonly CorModule module; + readonly CorType declaringType; + readonly CorValRef.ValueLoader loader; CorValRef cachedValue; public PropertyReference (EvaluationContext ctx, PropertyInfo prop, CorValRef thisobj, CorType declaringType) @@ -131,8 +130,7 @@ namespace MonoDevelop.Debugger.Win32 sb.Append ("]"); return sb.ToString (); } - else - return prop.Name; + return prop.Name; } } diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/StringAdaptor.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/StringAdaptor.cs index 022156ea3e..bba126a3eb 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/StringAdaptor.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/StringAdaptor.cs @@ -24,8 +24,6 @@ // THE SOFTWARE. // -using System; -using Mono.Debugging.Client; using Microsoft.Samples.Debugging.CorDebug; using Mono.Debugging.Evaluation; @@ -33,9 +31,9 @@ namespace MonoDevelop.Debugger.Win32 { public class StringAdaptor: IStringAdaptor { - CorEvaluationContext ctx; - CorStringValue str; - CorValRef obj; + readonly CorEvaluationContext ctx; + readonly CorStringValue str; + readonly CorValRef obj; public StringAdaptor (EvaluationContext ctx, CorValRef obj, CorStringValue str) { diff --git a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/VariableReference.cs b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/VariableReference.cs index bbd6038a05..ed1c5c1661 100644 --- a/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/VariableReference.cs +++ b/main/src/addins/MonoDevelop.Debugger.Win32/MonoDevelop.Debugger.Win32/VariableReference.cs @@ -25,19 +25,16 @@ // // -using System; using DC = Mono.Debugging.Client; using Mono.Debugging.Evaluation; -using Microsoft.Samples.Debugging.CorDebug; -using Microsoft.Samples.Debugging.CorDebug.NativeApi; namespace MonoDevelop.Debugger.Win32 { public class VariableReference: ValueReference { - CorValRef var; - DC.ObjectValueFlags flags; - string name; + readonly CorValRef var; + readonly DC.ObjectValueFlags flags; + readonly string name; public VariableReference (EvaluationContext ctx, CorValRef var, string name, DC.ObjectValueFlags flags) : base (ctx) diff --git a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ImmediatePad.cs b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ImmediatePad.cs index 45aca4fe75..19a157ac44 100644 --- a/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ImmediatePad.cs +++ b/main/src/addins/MonoDevelop.Debugger/MonoDevelop.Debugger/ImmediatePad.cs @@ -39,7 +39,7 @@ namespace MonoDevelop.Debugger { public class ImmediatePad: IPadContent { - static object locker = new object(); + static readonly object mutex = new object(); DebuggerConsoleView view; public void Initialize (IPadWindow container) @@ -230,7 +230,7 @@ namespace MonoDevelop.Debugger if (!val.IsEvaluating) { PrintChildValueAtMark (val, mark); - lock (locker) { + lock (mutex) { // Maybe We don't need this lock because children evaluation is done synchronously evaluatingList[val] = true; if (evaluatingList.All (x => x.Value)) diff --git a/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/HexEditorMargin.cs b/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/HexEditorMargin.cs index 5911b02d6d..c76528c8a2 100644 --- a/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/HexEditorMargin.cs +++ b/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/HexEditorMargin.cs @@ -104,7 +104,7 @@ namespace Mono.MHex.Rendering ISegment selection = Data.MainSelection.Segment; HandleSelection (selection.Offset, selection.EndOffset, startOffset, endOffset, null, delegate(long start, long end) { result.Layout.SetForeground (Style.Selection, (int)(start - startOffset) * 3, (int)(end - start) * 3 - 1); - result.Layout.SetBackgound (Style.SelectionBg, (int)(start - startOffset) * 3, (int)(end - start) * 3 - 1); + result.Layout.SetBackground (Style.SelectionBg, (int)(start - startOffset) * 3, (int)(end - start) * 3 - 1); }); } return result; diff --git a/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/TextEditorMargin.cs b/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/TextEditorMargin.cs index 92b2817d86..4a376c3fea 100644 --- a/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/TextEditorMargin.cs +++ b/main/src/addins/MonoDevelop.HexEditor/Mono.MHex.Rendering/TextEditorMargin.cs @@ -84,7 +84,7 @@ namespace Mono.MHex.Rendering ISegment selection = Data.MainSelection.Segment; HandleSelection (selection.Offset, selection.EndOffset, startOffset, endOffset, null, delegate(long start, long end) { result.Layout.SetForeground (Style.Selection, (int)(start - startOffset), (int)(end - start)); - result.Layout.SetBackgound (Style.SelectionBg, (int)(start - startOffset), (int)(end - start)); + result.Layout.SetBackground (Style.SelectionBg, (int)(start - startOffset), (int)(end - start)); }); } return result; diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/FixableResult.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/FixableResult.cs index 586e78ee50..7aaf76620f 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/FixableResult.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/FixableResult.cs @@ -63,6 +63,7 @@ namespace MonoDevelop.AnalysisCore string Label { get; } bool SupportsBatchFix { get; } DocumentRegion DocumentRegion { get; } + string IdString { get; } void Fix (); void BatchFix (); } diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/Fixes/GenericFix.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/Fixes/GenericFix.cs index 0cac96f30b..95ffb5231c 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/Fixes/GenericFix.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/Fixes/GenericFix.cs @@ -77,6 +77,7 @@ namespace MonoDevelop.AnalysisCore.Fixes Action batchFix; string label; public DocumentRegion DocumentRegion { get; set; } + public string IdString { get; set; } public GenericFix (string label, Action fix, Action batchFix = null) { diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/Fixes/RenameMemberFix.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/Fixes/RenameMemberFix.cs index ec3a57634a..baa31de769 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/Fixes/RenameMemberFix.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.AnalysisCore/Fixes/RenameMemberFix.cs @@ -41,7 +41,7 @@ namespace MonoDevelop.AnalysisCore.Fixes { public string NewName { get; private set; } public string OldName { get; private set; } - + public string IdString { get; set; } public IEntity Item { get; private set; } public RenameMemberFix (IEntity item, string oldName, string newName) @@ -114,6 +114,7 @@ namespace MonoDevelop.AnalysisCore.Fixes public bool Preview; public string Label { get; set; } public DocumentRegion DocumentRegion { get; set; } + public string IdString { get; set; } public void Fix () { diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/AnalysisCodeAction.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/AnalysisCodeAction.cs index 12f4111dc7..5641aecb60 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/AnalysisCodeAction.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/AnalysisCodeAction.cs @@ -78,6 +78,7 @@ namespace MonoDevelop.CodeActions Action = action; Title = action.Label; Result = result; + IdString = action.IdString; } public override void Run (IRefactoringContext context, object script) diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/CodeActionWidget.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/CodeActionWidget.cs index 3484e82739..c3bdc3eb03 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/CodeActionWidget.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeActions/CodeActionWidget.cs @@ -126,7 +126,12 @@ namespace MonoDevelop.CodeActions { int mnemonic = 1; bool gotImportantFix = false, addedSeparator = false; + var fixesAdded = new List<string> (); foreach (var fix_ in fixes.OrderByDescending (i => Tuple.Create (IsAnalysisOrErrorFix(i), (int)i.Severity, GetUsage (i.IdString)))) { + // filter out code actions that are already resolutions of a code issue + if (fixesAdded.Any (f => fix_.IdString.IndexOf (f, StringComparison.Ordinal) >= 0)) + continue; + fixesAdded.Add (fix_.IdString); if (IsAnalysisOrErrorFix (fix_)) gotImportantFix = true; if (!addedSeparator && gotImportantFix && !IsAnalysisOrErrorFix(fix_)) { diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeAnalysisRunner.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeAnalysisRunner.cs index 148667168d..9df6b86f5a 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeAnalysisRunner.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeAnalysisRunner.cs @@ -83,7 +83,7 @@ namespace MonoDevelop.CodeIssues if (severity == Severity.None || !provider.GetIsEnabled ()) continue; foreach (var r in provider.GetIssues (context, cancellationToken)) { - var fixes = new List<GenericFix> (r.Actions.Where (a => a != null).Select (a => { + var fixes = r.Actions == null ? new List<GenericFix> () : new List<GenericFix> (r.Actions.Where (a => a != null).Select (a => { Action batchAction = null; if (a.SupportsBatchRunning) batchAction = () => a.BatchRun (input, loc); @@ -95,7 +95,8 @@ namespace MonoDevelop.CodeIssues } }, batchAction) { - DocumentRegion = new DocumentRegion (r.Region.Begin, r.Region.End) + DocumentRegion = new DocumentRegion (r.Region.Begin, r.Region.End), + IdString = a.IdString }; })); result.Add (new InspectorResults ( diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeIssue.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeIssue.cs index bc9287a1d9..846f4dc678 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeIssue.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.CodeIssues/CodeIssue.cs @@ -77,6 +77,14 @@ namespace MonoDevelop.CodeIssues } /// <summary> + /// Gets or sets the code action providers for this issue. + /// </summary> + public IList<Type> ActionProvider { + get; + set; + } + + /// <summary> /// Initializes a new instance of the <see cref="MonoDevelop.CodeIssues.CodeIssue"/> class. /// </summary> public CodeIssue (IssueMarker issueMarker, string description, string fileName, DocumentLocation start, DocumentLocation end, string inspectorIdString, IEnumerable<MonoDevelop.CodeActions.CodeAction> actions = null) : this (issueMarker, description, new DomRegion (fileName, start, end), inspectorIdString, actions) diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.addin.xml b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.addin.xml index 9faab5b068..ad3e350a4b 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.addin.xml +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring.addin.xml @@ -22,7 +22,7 @@ </ExtensionPoint> <ExtensionPoint path = "/MonoDevelop/Refactoring/CodeIssues" name = "CodeIssue"> - <ExtensionNode name="CodeIssue" type ="MonoDevelop.CodeActions.CodeIssueAddinNode"/> + <ExtensionNode name="CodeIssue" type ="MonoDevelop.CodeIssues.CodeIssueAddinNode"/> </ExtensionPoint> <ExtensionPoint path = "/MonoDevelop/Refactoring/CodeIssueSource" name = "CodeIssueSource"> diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoryCommands.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoryCommands.cs index 29fb49d0a1..883a399964 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoryCommands.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/RefactoryCommands.cs @@ -284,7 +284,7 @@ namespace MonoDevelop.Refactoring lastLocation = loc; refactoringInfo.lastDocument = doc.ParsedDocument; } - if (refactoringInfo.validActions != null && refactoringInfo.lastDocument != null) { + if (refactoringInfo.validActions != null && refactoringInfo.lastDocument != null && refactoringInfo.lastDocument.CreateRefactoringContext != null) { var context = refactoringInfo.lastDocument.CreateRefactoringContext (doc, CancellationToken.None); foreach (var fix_ in refactoringInfo.validActions.OrderByDescending (i => Tuple.Create (CodeActionWidget.IsAnalysisOrErrorFix(i), (int)i.Severity, CodeActionWidget.GetUsage (i.IdString)))) { diff --git a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/ResolveCommandHandler.cs b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/ResolveCommandHandler.cs index 1824b9ca92..f62893b039 100644 --- a/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/ResolveCommandHandler.cs +++ b/main/src/addins/MonoDevelop.Refactoring/MonoDevelop.Refactoring/ResolveCommandHandler.cs @@ -158,7 +158,7 @@ namespace MonoDevelop.Refactoring return ""; string text = doc.Editor.GetTextAt (0, Math.Min (doc.Editor.Length, offset)); var stub = new StringBuilder (text); - CSharpCompletionEngine.AppendMissingClosingBrackets (stub, text, false); + CSharpCompletionEngine.AppendMissingClosingBrackets (stub, false); return stub.ToString (); } diff --git a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor.OptionPanels/CompletionCharactersPanel.cs b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor.OptionPanels/CompletionCharactersPanel.cs index 8e468eb21c..175d8528ed 100644 --- a/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor.OptionPanels/CompletionCharactersPanel.cs +++ b/main/src/addins/MonoDevelop.SourceEditor2/MonoDevelop.SourceEditor.OptionPanels/CompletionCharactersPanel.cs @@ -52,17 +52,17 @@ namespace MonoDevelop.SourceEditor.OptionPanels store = new ListStore (language, completeOnSpace, completeOnChars); var languageColumn = list.Columns.Add (GettextCatalog.GetString ("Language"), language); - languageColumn.IsResizeable = true; + languageColumn.CanResize = true; var checkBoxCellView = new CheckBoxCellView (completeOnSpace); checkBoxCellView.Editable = true; var completeOnSpaceColumn = list.Columns.Add (GettextCatalog.GetString ("Complete on space"), checkBoxCellView); - completeOnSpaceColumn.IsResizeable = true; + completeOnSpaceColumn.CanResize = true; var textCellView = new TextCellView (completeOnChars); textCellView.Editable = true; var doNotCompleteOnColumn = list.Columns.Add (GettextCatalog.GetString ("Do complete on"), textCellView); - doNotCompleteOnColumn.IsResizeable = true; + doNotCompleteOnColumn.CanResize = true; list.DataSource = store; PackStart (list, true, true); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Commands.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Commands.cs index 6817dd0c70..13b3fd9da2 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Commands.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Commands.cs @@ -55,8 +55,7 @@ namespace MonoDevelop.VersionControl.Git wob = IdeApp.ProjectOperations.CurrentSelectedWorkspaceItem; if (wob != null) return VersionControlService.GetRepository (wob) as GitRepository; - else - return null; + return null; } } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/CredentialsDialog.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/CredentialsDialog.cs index 11335cf52a..2060ad30d0 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/CredentialsDialog.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/CredentialsDialog.cs @@ -32,7 +32,7 @@ namespace MonoDevelop.VersionControl.Git { public partial class CredentialsDialog : Gtk.Dialog { - CredentialItem.YesNoType singleYesNoCred; + readonly CredentialItem.YesNoType singleYesNoCred; public CredentialsDialog (URIish uri, IEnumerable<CredentialItem> credentials) { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/EditBranchDialog.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/EditBranchDialog.cs index f3104e3d1b..4c821c249f 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/EditBranchDialog.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/EditBranchDialog.cs @@ -31,12 +31,12 @@ using MonoDevelop.Ide; namespace MonoDevelop.VersionControl.Git { - public partial class EditBranchDialog : Gtk.Dialog + public partial class EditBranchDialog : Dialog { - ListStore comboStore; - string currentTracking; - string oldName; - GitRepository repo; + readonly ListStore comboStore; + readonly string currentTracking; + readonly string oldName; + readonly GitRepository repo; public EditBranchDialog (GitRepository repo, Branch branch, bool isNew) { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/EditRemoteDialog.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/EditRemoteDialog.cs index 414d15d2da..73a8d6fec4 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/EditRemoteDialog.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/EditRemoteDialog.cs @@ -29,8 +29,8 @@ namespace MonoDevelop.VersionControl.Git { public partial class EditRemoteDialog : Gtk.Dialog { - RemoteSource remote; - bool updating; + readonly RemoteSource remote; + readonly bool updating; public EditRemoteDialog (RemoteSource remote, bool isNew) { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitClient.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitClient.cs index 6ea158091c..cf4d420d8a 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitClient.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitClient.cs @@ -24,15 +24,10 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. -using System; - namespace MonoDevelop.VersionControl.Git { public class GitClient : GitVersionControl { - public GitClient () - { - } } } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitConfigurationDialog.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitConfigurationDialog.cs index 8fbce49457..307bf8d946 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitConfigurationDialog.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitConfigurationDialog.cs @@ -32,11 +32,11 @@ using MonoDevelop.Components; namespace MonoDevelop.VersionControl.Git { - public partial class GitConfigurationDialog : Gtk.Dialog + public partial class GitConfigurationDialog : Dialog { - GitRepository repo; - ListStore storeBranches; - TreeStore storeRemotes; + readonly GitRepository repo; + readonly ListStore storeBranches; + readonly TreeStore storeRemotes; public GitConfigurationDialog (GitRepository repo) { @@ -101,7 +101,7 @@ namespace MonoDevelop.VersionControl.Git state.Load (); } - protected virtual void OnButtonAddBranchClicked (object sender, System.EventArgs e) + protected virtual void OnButtonAddBranchClicked (object sender, EventArgs e) { var dlg = new EditBranchDialog (repo, null, true); try { @@ -114,7 +114,7 @@ namespace MonoDevelop.VersionControl.Git } } - protected virtual void OnButtonEditBranchClicked (object sender, System.EventArgs e) + protected virtual void OnButtonEditBranchClicked (object sender, EventArgs e) { TreeIter it; if (!listBranches.Selection.GetSelected (out it)) @@ -138,7 +138,7 @@ namespace MonoDevelop.VersionControl.Git } } - protected virtual void OnButtonRemoveBranchClicked (object sender, System.EventArgs e) + protected virtual void OnButtonRemoveBranchClicked (object sender, EventArgs e) { TreeIter it; if (!listBranches.Selection.GetSelected (out it)) @@ -157,7 +157,7 @@ namespace MonoDevelop.VersionControl.Git } } - protected virtual void OnButtonSetDefaultBranchClicked (object sender, System.EventArgs e) + protected virtual void OnButtonSetDefaultBranchClicked (object sender, EventArgs e) { TreeIter it; if (!listBranches.Selection.GetSelected (out it)) @@ -167,12 +167,12 @@ namespace MonoDevelop.VersionControl.Git FillBranches (); } - protected virtual void OnButtonAddRemoteClicked (object sender, System.EventArgs e) + protected virtual void OnButtonAddRemoteClicked (object sender, EventArgs e) { var remote = new RemoteSource (); var dlg = new EditRemoteDialog (remote, true); try { - if (MessageService.RunCustomDialog (dlg) == (int) Gtk.ResponseType.Ok) { + if (MessageService.RunCustomDialog (dlg) == (int) ResponseType.Ok) { repo.AddRemote (remote, dlg.ImportTags); FillRemotes (); } @@ -181,7 +181,7 @@ namespace MonoDevelop.VersionControl.Git } } - protected virtual void OnButtonEditRemoteClicked (object sender, System.EventArgs e) + protected virtual void OnButtonEditRemoteClicked (object sender, EventArgs e) { TreeIter it; if (!treeRemotes.Selection.GetSelected (out it)) @@ -195,7 +195,7 @@ namespace MonoDevelop.VersionControl.Git var dlg = new EditRemoteDialog (remote, false); try { - if (MessageService.RunCustomDialog (dlg) == (int) Gtk.ResponseType.Ok) { + if (MessageService.RunCustomDialog (dlg) == (int) ResponseType.Ok) { if (remote.Name != oldName) repo.RenameRemote (oldName, remote.Name); repo.UpdateRemote (remote); @@ -206,7 +206,7 @@ namespace MonoDevelop.VersionControl.Git } } - protected virtual void OnButtonRemoveRemoteClicked (object sender, System.EventArgs e) + protected virtual void OnButtonRemoveRemoteClicked (object sender, EventArgs e) { TreeIter it; if (!treeRemotes.Selection.GetSelected (out it)) @@ -234,7 +234,7 @@ namespace MonoDevelop.VersionControl.Git buttonAddRemote.Sensitive = buttonEditRemote.Sensitive = buttonRemoveRemote.Sensitive = remote != null; } - protected virtual void OnButtonTrackRemoteClicked (object sender, System.EventArgs e) + protected virtual void OnButtonTrackRemoteClicked (object sender, EventArgs e) { TreeIter it; if (!treeRemotes.Selection.GetSelected (out it)) diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitCredentials.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitCredentials.cs index 67b9bbcd6e..82205c761c 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitCredentials.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitCredentials.cs @@ -24,7 +24,6 @@ // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. using System; -using System.Collections.Generic; using System.Linq; using MonoDevelop.Core; diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitNodeBuilderExtension.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitNodeBuilderExtension.cs index 9f381d8dce..2b242d9985 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitNodeBuilderExtension.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitNodeBuilderExtension.cs @@ -35,7 +35,7 @@ namespace MonoDevelop.VersionControl.Git { public class GitNodeBuilderExtension: NodeBuilderExtension { - Dictionary<FilePath,IWorkspaceObject> repos = new Dictionary<FilePath, IWorkspaceObject> (); + readonly Dictionary<FilePath,IWorkspaceObject> repos = new Dictionary<FilePath, IWorkspaceObject> (); protected override void Initialize () { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitRepository.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitRepository.cs index c761a5d072..b666f8739e 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitRepository.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitRepository.cs @@ -99,7 +99,7 @@ namespace MonoDevelop.VersionControl.Git public override bool IsUrlValid (string url) { try { - NGit.Transport.URIish u = new NGit.Transport.URIish (url); + URIish u = new URIish (url); if (!string.IsNullOrEmpty (u.GetHost ())) return true; } catch { @@ -186,15 +186,10 @@ namespace MonoDevelop.VersionControl.Git IEnumerable<IGrouping<NGit.Repository, FilePath>> GroupByRepository (IEnumerable<FilePath> files) { var cache = CachedSubmodules; - return files.GroupBy (f => { - return cache - .Where (s => { - var fullPath = s.Item1.ToAbsolute (RootPath); - return f.IsChildPathOf (fullPath) || f.CanonicalPath == fullPath.CanonicalPath; - }) - .Select (s => s.Item2) - .FirstOrDefault () ?? RootRepository; - }); + return files.GroupBy (f => cache.Where (s => { + var fullPath = s.Item1.ToAbsolute (RootPath); + return f.IsChildPathOf (fullPath) || f.CanonicalPath == fullPath.CanonicalPath; + }).Select (s => s.Item2).FirstOrDefault () ?? RootRepository); } protected override Revision[] OnGetHistory (FilePath localFile, Revision since) @@ -396,12 +391,12 @@ namespace MonoDevelop.VersionControl.Git protected override Repository OnPublish (string serverPath, FilePath localPath, FilePath[] files, string message, IProgressMonitor monitor) { // Initialize the repository - RootRepository = GitUtil.Init (localPath, Url, monitor); + RootRepository = GitUtil.Init (localPath, Url); NGit.Api.Git git = new NGit.Api.Git (RootRepository); try { var refs = git.Fetch ().Call ().GetAdvertisedRefs (); if (refs.Count > 0) { - throw new UserException ("The remote repository already contains branches. MonoDevelop can only publish to an empty repository"); + throw new UserException ("The remote repository already contains branches. Publishing is only possible to an empty repository"); } } catch { try { @@ -469,16 +464,18 @@ namespace MonoDevelop.VersionControl.Git throw new InvalidOperationException ("No remotes defined"); monitor.Log.WriteLine (GettextCatalog.GetString ("Fetching from '{0}'", remote)); - RemoteConfig remoteConfig = new RemoteConfig (RootRepository.GetConfig (), remote); - Transport tn = Transport.Open (RootRepository, remoteConfig); - using (var gm = new GitMonitor (monitor)) - tn.Fetch (gm, null); + var fetch = new NGit.Api.Git (RootRepository).Fetch (); + using (var gm = new GitMonitor (monitor)) { + fetch.SetRemote (remote); + fetch.SetProgressMonitor (gm); + fetch.Call (); + } monitor.Step (1); } - bool GetSubmodulesToUpdate (List<string> UpdateSubmodules) + bool GetSubmodulesToUpdate (List<string> updateSubmodules) { - List<string> DirtySubmodules = new List<string> (); + List<string> dirtySubmodules = new List<string> (); // Iterate submodules and do status. // SubmoduleStatus does not report changes for dirty submodules. @@ -488,14 +485,14 @@ namespace MonoDevelop.VersionControl.Git var status = statusCommand.Call (); if (status.IsClean ()) - UpdateSubmodules.Add (submodule.Item1); + updateSubmodules.Add (submodule.Item1); else - DirtySubmodules.Add (submodule.Item1); + dirtySubmodules.Add (submodule.Item1); } - if (DirtySubmodules.Count != 0) { + if (dirtySubmodules.Count != 0) { StringBuilder submodules = new StringBuilder (Environment.NewLine + Environment.NewLine); - foreach (var item in DirtySubmodules) + foreach (var item in dirtySubmodules) submodules.AppendLine (item); AlertButton response = MessageService.GenericAlert ( @@ -513,7 +510,7 @@ namespace MonoDevelop.VersionControl.Git return false; if (response == AlertButton.Yes) - UpdateSubmodules.AddRange (DirtySubmodules); + updateSubmodules.AddRange (dirtySubmodules); } return true; } @@ -550,7 +547,7 @@ namespace MonoDevelop.VersionControl.Git } if ((options & GitUpdateOptions.SaveLocalChanges) != GitUpdateOptions.SaveLocalChanges) { - VersionStatus unclean = VersionStatus.Modified | VersionStatus.ScheduledAdd | VersionStatus.ScheduledDelete; + const VersionStatus unclean = VersionStatus.Modified | VersionStatus.ScheduledAdd | VersionStatus.ScheduledDelete; bool modified = false; if (GetDirectoryVersionInfo (RootPath, false, true).Any (v => (v.Status & unclean) != VersionStatus.Unversioned)) modified = true; @@ -685,7 +682,7 @@ namespace MonoDevelop.VersionControl.Git monitor.Step (1); if ((options & GitUpdateOptions.SaveLocalChanges) != GitUpdateOptions.SaveLocalChanges) { - VersionStatus unclean = VersionStatus.Modified | VersionStatus.ScheduledAdd | VersionStatus.ScheduledDelete; + const VersionStatus unclean = VersionStatus.Modified | VersionStatus.ScheduledAdd | VersionStatus.ScheduledDelete; bool modified = false; if (GetDirectoryVersionInfo (RootPath, false, true).Any (v => (v.Status & unclean) != VersionStatus.Unversioned)) modified = true; @@ -853,7 +850,7 @@ namespace MonoDevelop.VersionControl.Git public void SetUserInfo (string name, string email) { - NGit.StoredConfig config = RootRepository.GetConfig (); + StoredConfig config = RootRepository.GetConfig (); config.SetString ("user", null, "name", name); config.SetString ("user", null, "email", email); config.Save (); @@ -885,6 +882,8 @@ namespace MonoDevelop.VersionControl.Git protected override void OnRevert (FilePath[] localPaths, bool recurse, IProgressMonitor monitor) { + // Replace with NGit.Api.Git.Reset () + // FIXME: we lack info about what happened to files foreach (var group in GroupByRepository (localPaths)) { var repository = group.Key; var files = group.ToArray (); @@ -929,7 +928,7 @@ namespace MonoDevelop.VersionControl.Git // We have to iterate through all folder files. We need a new iterator since the // existing rw is not recursive - r = new NGit.Treewalk.TreeWalk(repository); + r = new TreeWalk(repository); r.Reset (tree); r.Filter = PathFilterGroup.CreateFromStrings(new string[]{p}); r.Recursive = true; @@ -998,7 +997,7 @@ namespace MonoDevelop.VersionControl.Git var git = new NGit.Api.Git (GetRepository (localPath)); var gitRev = (GitRevision)revision; var revert = git.Revert ().Include (gitRev.Commit.ToObjectId ()); - var newRevision = revert.Call (); + revert.Call (); var revertResult = revert.GetFailingResult (); if (revertResult == null) { @@ -1042,7 +1041,7 @@ namespace MonoDevelop.VersionControl.Git } [Obsolete ("Use the overload with keepLocal parameter")] - protected override void OnDeleteFiles (FilePath[] path, bool force, IProgressMonitor monitor) + protected override void OnDeleteFiles (FilePath[] localPaths, bool force, IProgressMonitor monitor) { } @@ -1067,7 +1066,7 @@ namespace MonoDevelop.VersionControl.Git } [Obsolete ("Use the overload with keepLocal parameter")] - protected override void OnDeleteDirectories (FilePath[] path, bool force, IProgressMonitor monitor) + protected override void OnDeleteDirectories (FilePath[] localPaths, bool force, IProgressMonitor monitor) { } @@ -1141,29 +1140,26 @@ namespace MonoDevelop.VersionControl.Git ObjectId id = repository.Resolve (revision.ToString ()); RevWalk rw = new RevWalk (repository); RevCommit c = rw.ParseCommit (id); - if (c == null) - return string.Empty; - else - return GetCommitTextContent (c, repositoryPath); + return c == null ? string.Empty : GetCommitTextContent (c, repositoryPath); } - public override DiffInfo GenerateDiff (FilePath baseLocalPath, VersionInfo vi) + public override DiffInfo GenerateDiff (FilePath baseLocalPath, VersionInfo versionInfo) { try { var repository = GetRepository (baseLocalPath); - if ((vi.Status & VersionStatus.ScheduledAdd) != 0) { - var ctxt = GetFileContent (vi.LocalPath); - return new DiffInfo (baseLocalPath, vi.LocalPath, GenerateDiff (EmptyContent, ctxt)); - } else if ((vi.Status & VersionStatus.ScheduledDelete) != 0) { - var ctxt = GetCommitContent (GetHeadCommit (repository), vi.LocalPath); - return new DiffInfo (baseLocalPath, vi.LocalPath, GenerateDiff (ctxt, EmptyContent)); - } else if ((vi.Status & VersionStatus.Modified) != 0 || (vi.Status & VersionStatus.Conflicted) != 0) { - var ctxt1 = GetCommitContent (GetHeadCommit (repository), vi.LocalPath); - var ctxt2 = GetFileContent (vi.LocalPath); - return new DiffInfo (baseLocalPath, vi.LocalPath, GenerateDiff (ctxt1, ctxt2)); + if ((versionInfo.Status & VersionStatus.ScheduledAdd) != 0) { + var ctxt = GetFileContent (versionInfo.LocalPath); + return new DiffInfo (baseLocalPath, versionInfo.LocalPath, GenerateDiff (EmptyContent, ctxt)); + } else if ((versionInfo.Status & VersionStatus.ScheduledDelete) != 0) { + var ctxt = GetCommitContent (GetHeadCommit (repository), versionInfo.LocalPath); + return new DiffInfo (baseLocalPath, versionInfo.LocalPath, GenerateDiff (ctxt, EmptyContent)); + } else if ((versionInfo.Status & VersionStatus.Modified) != 0 || (versionInfo.Status & VersionStatus.Conflicted) != 0) { + var ctxt1 = GetCommitContent (GetHeadCommit (repository), versionInfo.LocalPath); + var ctxt2 = GetFileContent (versionInfo.LocalPath); + return new DiffInfo (baseLocalPath, versionInfo.LocalPath, GenerateDiff (ctxt1, ctxt2)); } } catch (Exception ex) { - LoggingService.LogError ("Could not get diff for file '" + vi.LocalPath + "'", ex); + LoggingService.LogError ("Could not get diff for file '" + versionInfo.LocalPath + "'", ex); } return null; } @@ -1269,33 +1265,39 @@ namespace MonoDevelop.VersionControl.Git public void Push (IProgressMonitor monitor, string remote, string remoteBranch) { - RemoteConfig remoteConfig = new RemoteConfig (RootRepository.GetConfig (), remote); - Transport tp = Transport.Open (RootRepository, remoteConfig); - string remoteRef = "refs/heads/" + remoteBranch; - - RemoteRefUpdate rr = new RemoteRefUpdate (RootRepository, RootRepository.GetBranch (), remoteRef, false, null, null); - List<RemoteRefUpdate> list = new List<RemoteRefUpdate> (); - list.Add (rr); - using (var gm = new GitMonitor (monitor)) - tp.Push (gm, list); - switch (rr.GetStatus ()) { - case RemoteRefUpdate.Status.UP_TO_DATE: monitor.ReportSuccess (GettextCatalog.GetString ("Remote branch is up to date.")); break; - case RemoteRefUpdate.Status.REJECTED_NODELETE: monitor.ReportError (GettextCatalog.GetString ("The server is configured to deny deletion of the branch"), null); break; - case RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD: monitor.ReportError (GettextCatalog.GetString ("The update is a non-fast-forward update. Merge the remote changes before pushing again."), null); break; - case RemoteRefUpdate.Status.OK: - monitor.ReportSuccess (GettextCatalog.GetString ("Push operation successfully completed.")); - // Update the remote branch - ObjectId headId = rr.GetNewObjectId (); - RefUpdate updateRef = RootRepository.UpdateRef (Constants.R_REMOTES + remote + "/" + remoteBranch); - updateRef.SetNewObjectId(headId); - updateRef.Update(); - break; - default: - string msg = rr.GetMessage (); - msg = !string.IsNullOrEmpty (msg) ? msg : GettextCatalog.GetString ("Push operation failed"); - monitor.ReportError (msg, null); - break; + IEnumerable<PushResult> res; + + var push = new NGit.Api.Git (RootRepository).Push (); + + // We only have one pushed branch. + push.SetRemote (remote).SetRefSpecs (new RefSpec (remoteRef)); + using (var gm = new GitMonitor (monitor)) { + push.SetProgressMonitor (gm); + res = push.Call (); + } + + foreach (var pr in res) { + var remoteUpdate = pr.GetRemoteUpdate (remoteRef); + + switch (remoteUpdate.GetStatus ()) { + case RemoteRefUpdate.Status.UP_TO_DATE: monitor.ReportSuccess (GettextCatalog.GetString ("Remote branch is up to date.")); break; + case RemoteRefUpdate.Status.REJECTED_NODELETE: monitor.ReportError (GettextCatalog.GetString ("The server is configured to deny deletion of the branch"), null); break; + case RemoteRefUpdate.Status.REJECTED_NONFASTFORWARD: monitor.ReportError (GettextCatalog.GetString ("The update is a non-fast-forward update. Merge the remote changes before pushing again."), null); break; + case RemoteRefUpdate.Status.OK: + monitor.ReportSuccess (GettextCatalog.GetString ("Push operation successfully completed.")); + // Update the remote branch + ObjectId headId = remoteUpdate.GetNewObjectId (); + RefUpdate updateRef = RootRepository.UpdateRef (Constants.R_REMOTES + remote + "/" + remoteBranch); + updateRef.SetNewObjectId(headId); + updateRef.Update(); + break; + default: + string msg = remoteUpdate.GetMessage (); + msg = !string.IsNullOrEmpty (msg) ? msg : GettextCatalog.GetString ("Push operation failed"); + monitor.ReportError (msg, null); + break; + } } } @@ -1397,9 +1399,9 @@ namespace MonoDevelop.VersionControl.Git public IEnumerable<Branch> GetBranches () { - IDictionary<string, NGit.Ref> refs = RootRepository.RefDatabase.GetRefs (Constants.R_HEADS); - foreach (var pair in refs) { - string name = NGit.Repository.ShortenRefName (pair.Key); + var list = new NGit.Api.Git (RootRepository).BranchList ().SetListMode (ListBranchCommand.ListMode.HEAD); + foreach (var item in list.Call ()) { + string name = NGit.Repository.ShortenRefName (item.GetName ()); Branch br = new Branch (); br.Name = name; br.Tracking = GitUtil.GetUpstreamSource (RootRepository, name); @@ -1409,14 +1411,18 @@ namespace MonoDevelop.VersionControl.Git public IEnumerable<string> GetTags () { - return RootRepository.GetTags ().Keys; + var list = new NGit.Api.Git (RootRepository).TagList (); + foreach (var item in list.Call ()) { + string name = NGit.Repository.ShortenRefName (item.GetName ()); + yield return name; + } } public IEnumerable<string> GetRemoteBranches (string remoteName) { - var refs = RootRepository.RefDatabase.GetRefs (Constants.R_REMOTES); - foreach (var pair in refs) { - string name = NGit.Repository.ShortenRefName (pair.Key); + var list = new NGit.Api.Git (RootRepository).BranchList ().SetListMode (ListBranchCommand.ListMode.REMOTE); + foreach (var item in list.Call ()) { + string name = NGit.Repository.ShortenRefName (item.GetName ()); if (name.StartsWith (remoteName + "/", StringComparison.Ordinal)) yield return name.Substring (remoteName.Length + 1); } @@ -1453,45 +1459,25 @@ namespace MonoDevelop.VersionControl.Git monitor.Step (1); } - + + // Replace with NGit.Api.Git ().Checkout () // Switch to the target branch - DirCache dc = RootRepository.LockDirCache (); + var checkout = new NGit.Api.Git (RootRepository).Checkout (); + checkout.SetName (branch); try { - RevWalk rw = new RevWalk (RootRepository); - ObjectId branchHeadId = RootRepository.Resolve (branch); - if (branchHeadId == null) - throw new InvalidOperationException ("Branch head commit not found"); - - RevCommit branchCommit = rw.ParseCommit (branchHeadId); - DirCacheCheckout checkout = new DirCacheCheckout (RootRepository, null, dc, branchCommit.Tree); - checkout.Checkout (); - - RefUpdate u = RootRepository.UpdateRef(Constants.HEAD); - u.Link ("refs/heads/" + branch); - monitor.Step (1); - } catch { - dc.Unlock (); + checkout.Call (); + } finally { + // Restore the branch stash if (GitService.StashUnstashWhenSwitchingBranches) { - // If something goes wrong, restore the work tree status - using (var gm = new GitMonitor (monitor)) - stash.Apply (gm); - stashes.Remove (stash); - } - throw; - } - - // Restore the branch stash - - if (GitService.StashUnstashWhenSwitchingBranches) { - stash = GetStashForBranch (stashes, branch); - if (stash != null) { - using (var gm = new GitMonitor (monitor)) - stash.Apply (gm); - stashes.Remove (stash); + stash = GetStashForBranch (stashes, branch); + if (stash != null) { + using (var gm = new GitMonitor (monitor)) + stash.Apply (gm); + stashes.Remove (stash); + } + monitor.Step (1); } - monitor.Step (1); } - // Notify file changes NotifyFileChanges (monitor, statusList); @@ -1658,13 +1644,13 @@ namespace MonoDevelop.VersionControl.Git internal GitRevision GetPreviousRevisionFor (GitRevision revision) { - ObjectId id = revision.GitRepository.Resolve (revision.ToString () + "^"); + ObjectId id = revision.GitRepository.Resolve (revision + "^"); if (id == null) return null; return new GitRevision (this, revision.GitRepository, id.Name); } - protected override void OnIgnore (FilePath[] paths) + protected override void OnIgnore (FilePath[] localPath) { List<FilePath> ignored = new List<FilePath> (); string gitignore = RootPath + Path.DirectorySeparatorChar + ".gitignore"; @@ -1678,13 +1664,13 @@ namespace MonoDevelop.VersionControl.Git } StringBuilder sb = new StringBuilder (); - foreach (var path in paths.Except (ignored)) + foreach (var path in localPath.Except (ignored)) sb.AppendLine (RootRepository.ToGitPath (path)); File.AppendAllText (RootPath + Path.DirectorySeparatorChar + ".gitignore", sb.ToString ()); } - protected override void OnUnignore (FilePath[] paths) + protected override void OnUnignore (FilePath[] localPath) { List<string> ignored = new List<string> (); string gitignore = RootPath + Path.DirectorySeparatorChar + ".gitignore"; @@ -1698,7 +1684,7 @@ namespace MonoDevelop.VersionControl.Git } StringBuilder sb = new StringBuilder (); - foreach (var path in ignored.Except (RootRepository.ToGitPath (paths))) + foreach (var path in ignored.Except (RootRepository.ToGitPath (localPath))) sb.AppendLine (path); File.WriteAllText (RootPath + Path.DirectorySeparatorChar + ".gitignore", sb.ToString ()); @@ -1707,7 +1693,7 @@ namespace MonoDevelop.VersionControl.Git public class GitRevision: Revision { - string rev; + readonly string rev; internal RevCommit Commit { get; set; } internal FilePath FileForChanges { get; set; } @@ -1735,10 +1721,7 @@ namespace MonoDevelop.VersionControl.Git public override string ShortName { get { - if (rev.Length > 10) - return rev.Substring (0, 10); - else - return rev; + return rev.Length > 10 ? rev.Substring (0, 10) : rev; } } @@ -1795,9 +1778,9 @@ namespace MonoDevelop.VersionControl.Git public string PushUrl { get; internal set; } } - class GitMonitor: NGit.ProgressMonitor, IDisposable + class GitMonitor: ProgressMonitor, IDisposable { - IProgressMonitor monitor; + readonly IProgressMonitor monitor; int currentWork; int currentStep; bool taskStarted; diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitSupportFeature.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitSupportFeature.cs index 546d77cf65..eec6e6206f 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitSupportFeature.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitSupportFeature.cs @@ -64,7 +64,7 @@ namespace MonoDevelop.VersionControl.Git { Solution sol = (Solution)o; sol.Saved -= OnSolutionSaved; - GitUtil.Init (sol.BaseDirectory, null, null); + GitUtil.Init (sol.BaseDirectory, null); GitRepository gitRepo = new GitRepository (sol.BaseDirectory, null); gitRepo.Add (sol.GetItemFiles (true).ToArray (), false, new MonoDevelop.Core.ProgressMonitoring.NullProgressMonitor ()); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitUtil.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitUtil.cs index 67846cbb65..dee30960cf 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitUtil.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitUtil.cs @@ -189,12 +189,6 @@ namespace MonoDevelop.VersionControl.Git } } - public static void Checkout (NGit.Repository repo, RevCommit commit, string working_directory) - { - DirCacheCheckout co = new DirCacheCheckout (repo, null, repo.ReadDirCache (), commit.Tree); - co.Checkout (); - } - public static StashCollection GetStashes (NGit.Repository repo) { return new StashCollection (repo); @@ -260,7 +254,7 @@ namespace MonoDevelop.VersionControl.Git config.Save (); } - public static LocalGitRepository Init (string targetLocalPath, string url, IProgressMonitor monitor) + public static LocalGitRepository Init (string targetLocalPath, string url) { InitCommand ci = new InitCommand (); ci.SetDirectory (targetLocalPath); @@ -293,9 +287,9 @@ namespace MonoDevelop.VersionControl.Git return repo; } - public static MergeCommandResult MergeTrees (NGit.ProgressMonitor monitor, NGit.Repository repo, RevCommit srcBase, RevCommit srcCommit, string sourceDisplayName, bool commitResult) + public static MergeCommandResult MergeTrees (ProgressMonitor monitor, NGit.Repository repo, RevCommit srcBase, RevCommit srcCommit, string sourceDisplayName, bool commitResult) { - RevCommit newHead = null; + RevCommit newHead; RevWalk revWalk = new RevWalk(repo); try { @@ -316,11 +310,11 @@ namespace MonoDevelop.VersionControl.Git merger.SetBase(srcBase); bool noProblems; - IDictionary<string, MergeResult<NGit.Diff.Sequence>> lowLevelResults = null; + IDictionary<string, MergeResult<Sequence>> lowLevelResults = null; IDictionary<string, ResolveMerger.MergeFailureReason> failingPaths = null; IList<string> modifiedFiles = null; - ResolveMerger resolveMerger = (ResolveMerger)merger; + ResolveMerger resolveMerger = merger; resolveMerger.SetCommitNames(new string[] { "BASE", "HEAD", sourceDisplayName }); noProblems = merger.Merge(headCommit, srcCommit); lowLevelResults = resolveMerger.GetMergeResults(); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitVersionControl.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitVersionControl.cs index e92a884c34..62c70d095b 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitVersionControl.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/GitVersionControl.cs @@ -31,7 +31,7 @@ namespace MonoDevelop.VersionControl.Git { public abstract class GitVersionControl : VersionControlSystem { - Dictionary<FilePath,GitRepository> repositories = new Dictionary<FilePath,GitRepository> (); + readonly Dictionary<FilePath,GitRepository> repositories = new Dictionary<FilePath,GitRepository> (); static GitVersionControl () { @@ -59,8 +59,7 @@ namespace MonoDevelop.VersionControl.Git repositories [path.CanonicalPath] = repo = new GitRepository (path, null); return repo; } - else - return GetRepositoryReference (path.ParentDirectory, id); + return GetRepositoryReference (path.ParentDirectory, id); } protected override Repository OnCreateRepositoryInstance () diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/MergeDialog.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/MergeDialog.cs index 7051f5ac6c..a6f5be0c69 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/MergeDialog.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/MergeDialog.cs @@ -31,13 +31,13 @@ using MonoDevelop.Ide; namespace MonoDevelop.VersionControl.Git { - public partial class MergeDialog : Gtk.Dialog + public partial class MergeDialog : Dialog { - TreeStore store; - GitRepository repo; + readonly TreeStore store; + readonly GitRepository repo; string currentSel; string currentType; - bool rebasing; + readonly bool rebasing; public MergeDialog (GitRepository repo, bool rebasing) { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/PushDialog.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/PushDialog.cs index e6d255a3d5..c35fefdb5e 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/PushDialog.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/PushDialog.cs @@ -31,7 +31,7 @@ namespace MonoDevelop.VersionControl.Git { public partial class PushDialog : Gtk.Dialog { - GitRepository repo; + readonly GitRepository repo; public PushDialog (GitRepository repo) { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Stash.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Stash.cs index 4376e83a23..ccf2f2e338 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Stash.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/Stash.cs @@ -143,7 +143,7 @@ namespace MonoDevelop.VersionControl.Git return s; } - public MergeCommandResult Apply (NGit.ProgressMonitor monitor) + public MergeCommandResult Apply (ProgressMonitor monitor) { return StashCollection.Apply (monitor, this); } @@ -151,7 +151,7 @@ namespace MonoDevelop.VersionControl.Git public class StashCollection: IEnumerable<Stash> { - NGit.Repository _repo; + readonly NGit.Repository _repo; internal StashCollection (NGit.Repository repo) { @@ -173,12 +173,12 @@ namespace MonoDevelop.VersionControl.Git } } - public Stash Create (NGit.ProgressMonitor monitor) + public Stash Create (ProgressMonitor monitor) { return Create (monitor, null); } - public Stash Create (NGit.ProgressMonitor monitor, string message) + public Stash Create (ProgressMonitor monitor, string message) { if (monitor != null) { monitor.Start (1); @@ -194,7 +194,7 @@ namespace MonoDevelop.VersionControl.Git if (string.IsNullOrEmpty (message)) { // Use the commit summary as message - message = parent.Abbreviate (7).ToString () + " " + parent.GetShortMessage (); + message = parent.Abbreviate (7) + " " + parent.GetShortMessage (); int i = message.IndexOfAny (new char[] { '\r', '\n' }); if (i != -1) message = message.Substring (0, i); @@ -300,7 +300,7 @@ namespace MonoDevelop.VersionControl.Git } } - internal MergeCommandResult Apply (NGit.ProgressMonitor monitor, Stash stash) + internal MergeCommandResult Apply (ProgressMonitor monitor, Stash stash) { monitor.Start (1); monitor.BeginTask ("Applying stash", 100); @@ -320,7 +320,7 @@ namespace MonoDevelop.VersionControl.Git Remove (stashes, s); } - public MergeCommandResult Pop (NGit.ProgressMonitor monitor) + public MergeCommandResult Pop (ProgressMonitor monitor) { List<Stash> stashes = ReadStashes (); Stash last = stashes.Last (); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/StashManagerDialog.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/StashManagerDialog.cs index 5111961d7c..6680f8ec65 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/StashManagerDialog.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Git/MonoDevelop.VersionControl.Git/StashManagerDialog.cs @@ -30,10 +30,10 @@ using MonoDevelop.Ide; namespace MonoDevelop.VersionControl.Git { - public partial class StashManagerDialog : Gtk.Dialog + public partial class StashManagerDialog : Dialog { - ListStore store; - StashCollection stashes; + readonly ListStore store; + readonly StashCollection stashes; public StashManagerDialog (GitRepository repo) { diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient0.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient0.cs index 5b25e1cb12..2903cf2b4e 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient0.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient0.cs @@ -302,7 +302,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix { { return svn_client_get_wc_root (out wcroot_abspath, local_abspath, ctx, result_pool, scratch_pool); } - + public override IntPtr strerror (int statcode, byte[] buf, int bufsize) { return svn_strerror (statcode, buf, bufsize); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient1.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient1.cs index 2a35df1fea..7dbfd2d9ff 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient1.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/LibSvnClient1.cs @@ -303,7 +303,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix { { return svn_client_get_wc_root (out wcroot_abspath, local_abspath, ctx, result_pool, scratch_pool); } - + public override IntPtr strerror (int statcode, byte[] buf, int bufsize) { return svn_strerror (statcode, buf, bufsize); diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/SvnClient.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/SvnClient.cs index 51aef5eefa..3e1aa611bf 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/SvnClient.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion.Unix/MonoDevelop.VersionControl.Subversion.Unix/SvnClient.cs @@ -17,9 +17,26 @@ namespace MonoDevelop.VersionControl.Subversion.Unix { public class SvnClient : SubversionVersionControl { - internal static LibApr apr; - static Lazy<bool> isInstalled; - internal static LibSvnClient svn; + static LibApr apr; + static readonly Lazy<bool> isInstalled; + static LibSvnClient svn; + static readonly Lazy<bool> pre_1_7; + + internal static LibApr Apr { + get { + if (apr == null) + CheckInstalled (); + return apr; + } + } + + internal static LibSvnClient Svn { + get { + if (svn == null) + CheckInstalled (); + return svn; + } + } internal static void CheckError (IntPtr error) { @@ -55,7 +72,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix return error.message; else { byte[] buf = new byte [300]; - svn.strerror (error.apr_err, buf, buf.Length); + Svn.strerror (error.apr_err, buf, buf.Length); return Encoding.UTF8.GetString (buf); } } @@ -63,7 +80,8 @@ namespace MonoDevelop.VersionControl.Subversion.Unix internal static IntPtr newpool (IntPtr parent) { IntPtr p; - apr.pool_create_ex (out p, parent, IntPtr.Zero, IntPtr.Zero); + + Apr.pool_create_ex (out p, parent, IntPtr.Zero, IntPtr.Zero); if (p == IntPtr.Zero) throw new InvalidOperationException ("Could not create an APR pool."); return p; @@ -73,7 +91,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix { if (pathOrUrl == null) return null; - IntPtr res = svn.path_internal_style (pathOrUrl, localpool); + IntPtr res = Svn.path_internal_style (pathOrUrl, localpool); return Marshal.PtrToStringAnsi (res); } @@ -98,7 +116,19 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } return true; } - + + internal static bool CheckVersion () + { + return GetVersion ().StartsWith ("1.6", StringComparison.Ordinal); + } + + public static string GetVersion () + { + IntPtr ptr = Svn.client_version (); + LibSvnClient.svn_version_t ver = (LibSvnClient.svn_version_t)Marshal.PtrToStructure (ptr, typeof(LibSvnClient.svn_version_t)); + return ver.major + "." + ver.minor + "." + ver.patch; + } + static int GetLoadAprLib (int oldVersion) { // Get the version of the loaded libapr @@ -123,9 +153,14 @@ namespace MonoDevelop.VersionControl.Subversion.Unix get { return isInstalled.Value; } } + public static bool Pre_1_7 { + get { return pre_1_7.Value; } + } + static SvnClient () { isInstalled = new Lazy<bool> (CheckInstalled); + pre_1_7 = new Lazy<bool> (CheckVersion); } public override SubversionBackend CreateBackend () @@ -142,9 +177,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix IntPtr localpool = newpool (IntPtr.Zero); try { string npath = NormalizePath (path, localpool); - CheckError (svn.client_url_from_path (ref ret, npath, localpool)); + CheckError (Svn.client_url_from_path (ref ret, npath, localpool)); } finally { - apr.pool_destroy (localpool); + Apr.pool_destroy (localpool); } if (ret == IntPtr.Zero) @@ -155,26 +190,28 @@ namespace MonoDevelop.VersionControl.Subversion.Unix public override string GetDirectoryDotSvn (FilePath path) { - UnixSvnBackend backend = CreateBackend () as UnixSvnBackend; - bool pre_1_7; - string new_path = backend.GetDirectoryDotSvnInternal (path, out pre_1_7); - if (pre_1_7) + if (Pre_1_7) return base.GetDirectoryDotSvn (path); - return new_path; + + UnixSvnBackend backend = CreateBackend () as UnixSvnBackend; + if (backend == null) + return String.Empty; + + return backend.GetDirectoryDotSvnInternal (path); } } public class UnixSvnBackend : SubversionBackend { protected static LibApr apr { - get { return SvnClient.apr; } + get { + return SvnClient.Apr; + } } protected static LibSvnClient svn { get { - if (SvnClient.svn == null) - SvnClient.CheckInstalled (); - return SvnClient.svn; + return SvnClient.Svn; } } @@ -193,29 +230,28 @@ namespace MonoDevelop.VersionControl.Subversion.Unix return SvnClient.newpool (parent); } - bool pre_1_7; - bool disposed = false; - IntPtr auth_baton; - IntPtr pool; - IntPtr ctx; + bool disposed; + readonly IntPtr auth_baton; + readonly IntPtr pool; + readonly IntPtr ctx; - object sync = new object(); - bool inProgress = false; + readonly object sync = new object(); + bool inProgress; IProgressMonitor updatemonitor; ArrayList updateFileList; - string commitmessage = null; + string commitmessage; ArrayList lockFileList; LibSvnClient.NotifyLockState requiredLockState; // retain this so the delegates aren't GC'ed - LibSvnClient.svn_cancel_func_t cancel_func; - LibSvnClient.svn_ra_progress_notify_func_t progress_func; - LibSvnClient.svn_wc_notify_func2_t notify_func; - LibSvnClient.svn_client_get_commit_log_t log_func; - IntPtr config_hash; - IntPtr wc_ctx; + readonly LibSvnClient.svn_cancel_func_t cancel_func; + readonly LibSvnClient.svn_ra_progress_notify_func_t progress_func; + readonly LibSvnClient.svn_wc_notify_func2_t notify_func; + readonly LibSvnClient.svn_client_get_commit_log_t log_func; + readonly IntPtr config_hash; + readonly IntPtr wc_ctx; static bool IsBinary (byte[] buffer, long length) { @@ -228,7 +264,6 @@ namespace MonoDevelop.VersionControl.Subversion.Unix public UnixSvnBackend () { - pre_1_7 = GetVersion ().StartsWith ("1.6", StringComparison.Ordinal); // Allocate the APR pool and the SVN client context. pool = newpool (IntPtr.Zero); @@ -237,7 +272,10 @@ namespace MonoDevelop.VersionControl.Subversion.Unix // for the authentication providers don't exist, authentication // data won't be saved and no error is given. svn.config_ensure (null, pool); - + + // Load user and system configuration + svn.config_get_config (ref config_hash, null, pool); + if (svn.client_create_context (out ctx, pool) != IntPtr.Zero) throw new InvalidOperationException ("Could not create a Subversion client context."); @@ -259,16 +297,13 @@ namespace MonoDevelop.VersionControl.Subversion.Unix (int) Marshal.OffsetOf (typeof (LibSvnClient.svn_client_ctx_t), "cancel_func"), Marshal.GetFunctionPointerForDelegate (cancel_func)); - - // Load user and system configuration - svn.config_get_config (ref config_hash, null, pool); Marshal.WriteIntPtr (ctx, (int) Marshal.OffsetOf (typeof (LibSvnClient.svn_client_ctx_t), "config"), config_hash); - if (!pre_1_7) { + if (!SvnClient.Pre_1_7) { IntPtr scratch = newpool (IntPtr.Zero); - svn.wc_context_create (out wc_ctx, config_hash, pool, scratch); + svn.wc_context_create (out wc_ctx, IntPtr.Zero, pool, scratch); Marshal.WriteIntPtr (ctx, (int) Marshal.OffsetOf (typeof (LibSvnClient.svn_client_ctx_t), "wc_ctx"), wc_ctx); @@ -353,7 +388,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix return apr.pcalloc (localpool, error); } - static LibSvnClient.svn_auth_simple_prompt_func_t OnAuthSimplePromptCallback = OnAuthSimplePrompt; + static readonly LibSvnClient.svn_auth_simple_prompt_func_t OnAuthSimplePromptCallback = OnAuthSimplePrompt; static IntPtr OnAuthSimplePrompt (ref IntPtr cred, IntPtr baton, string realm, string user_name, bool may_save, IntPtr pool) { LibSvnClient.svn_auth_cred_simple_t data = new LibSvnClient.svn_auth_cred_simple_t ();
@@ -371,7 +406,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } } - static LibSvnClient.svn_auth_username_prompt_func_t OnAuthUsernamePromptCallback = OnAuthUsernamePrompt; + static readonly LibSvnClient.svn_auth_username_prompt_func_t OnAuthUsernamePromptCallback = OnAuthUsernamePrompt; static IntPtr OnAuthUsernamePrompt (ref IntPtr cred, IntPtr baton, string realm, bool may_save, IntPtr pool) { LibSvnClient.svn_auth_cred_username_t data = new LibSvnClient.svn_auth_cred_username_t (); @@ -389,7 +424,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } } - static LibSvnClient.svn_auth_ssl_server_trust_prompt_func_t OnAuthSslServerTrustPromptCallback = OnAuthSslServerTrustPrompt; + static readonly LibSvnClient.svn_auth_ssl_server_trust_prompt_func_t OnAuthSslServerTrustPromptCallback = OnAuthSslServerTrustPrompt; static IntPtr OnAuthSslServerTrustPrompt (ref IntPtr cred, IntPtr baton, string realm, UInt32 failures, ref LibSvnClient.svn_auth_ssl_server_cert_info_t cert_info, bool may_save, IntPtr pool) { LibSvnClient.svn_auth_cred_ssl_server_trust_t data = new LibSvnClient.svn_auth_cred_ssl_server_trust_t (); @@ -417,7 +452,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } } - static LibSvnClient.svn_auth_ssl_client_cert_prompt_func_t OnAuthSslClientCertPromptCallback = OnAuthSslClientCertPrompt; + static readonly LibSvnClient.svn_auth_ssl_client_cert_prompt_func_t OnAuthSslClientCertPromptCallback = OnAuthSslClientCertPrompt; static IntPtr OnAuthSslClientCertPrompt (ref IntPtr cred, IntPtr baton, string realm, bool may_save, IntPtr pool) { LibSvnClient.svn_auth_cred_ssl_client_cert_t data = new LibSvnClient.svn_auth_cred_ssl_client_cert_t ();
@@ -434,7 +469,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } } - static LibSvnClient.svn_auth_ssl_client_cert_pw_prompt_func_t OnAuthSslClientCertPwPromptCallback = OnAuthSslClientCertPwPrompt; + static readonly LibSvnClient.svn_auth_ssl_client_cert_pw_prompt_func_t OnAuthSslClientCertPwPromptCallback = OnAuthSslClientCertPwPrompt; static IntPtr OnAuthSslClientCertPwPrompt (ref IntPtr cred, IntPtr baton, string realm, bool may_save, IntPtr pool) { LibSvnClient.svn_auth_cred_ssl_client_cert_pw_t data;
@@ -455,9 +490,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix public override string GetVersion () { - IntPtr ptr = svn.client_version (); - LibSvnClient.svn_version_t ver = (LibSvnClient.svn_version_t) Marshal.PtrToStructure (ptr, typeof (LibSvnClient.svn_version_t)); - return ver.major + "." + ver.minor + "." + ver.patch; + return SvnClient.GetVersion (); } public override IEnumerable<DirectoryEntry> List (FilePath path, bool recurse, SvnRevision rev) @@ -470,9 +503,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix return SvnClient.NormalizePath (pathOrUrl, localpool); } - public override IEnumerable<DirectoryEntry> ListUrl (string pathorurl, bool recurse, SvnRevision rev) + public override IEnumerable<DirectoryEntry> ListUrl (string url, bool recurse, SvnRevision rev) { - if (pathorurl == null) + if (url == null) throw new ArgumentNullException (); LibSvnClient.Rev revision = (LibSvnClient.Rev) rev; @@ -482,9 +515,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix try { IntPtr hash; - pathorurl = NormalizePath (pathorurl, localpool); + url = NormalizePath (url, localpool); - CheckError (svn.client_ls (out hash, pathorurl, ref revision, + CheckError (svn.client_ls (out hash, url, ref revision, recurse, ctx, localpool)); IntPtr item = apr.hash_first (localpool, hash); @@ -613,16 +646,16 @@ namespace MonoDevelop.VersionControl.Subversion.Unix return annotations; } - public override string GetTextAtRevision (string pathorurl, Revision revision) + public override string GetTextAtRevision (string repositoryPath, Revision revision) { return null; } - public override string GetTextAtRevision (string pathorurl, Revision revision, string rootPath) + public override string GetTextAtRevision (string repositoryPath, Revision revision, string rootPath) { MemoryStream memstream = new MemoryStream (); try { - Cat (pathorurl, (SvnRevision) revision, memstream); + Cat (repositoryPath, (SvnRevision) revision, memstream); } catch (SubversionException e) { // File got added/removed at some point. // SVN_ERR_FS_NOT_FOUND @@ -714,21 +747,6 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } }
- public override void Resolve (FilePath path, bool recurse, IProgressMonitor monitor) - { - if (path == FilePath.Null || monitor == null) - throw new ArgumentNullException(); - - var localpool = TryStartOperation (monitor); - try { - string pathorurl = NormalizePath (path, localpool); - CheckError (svn.client_resolved (pathorurl, recurse, ctx, localpool)); - } finally { - apr.pool_destroy (localpool); - TryEndOperation (); - } - }
-
public override void Add (FilePath path, bool recurse, IProgressMonitor monitor) { if (path == FilePath.Null || monitor == null) @@ -1290,14 +1308,14 @@ namespace MonoDevelop.VersionControl.Subversion.Unix break; // case LibSvnClient.NotifyAction.Exists: // // original is untranslated, we'll make it a bit shorter -///* actiondesc = data.content_state == LibSvnClient.NotifyState.Conflicted ? "C" : "E"; +// actiondesc = data.content_state == LibSvnClient.NotifyState.Conflicted ? "C" : "E"; // if (data.prop_state == LibSvnClient.NotifyState.Conflicted) { // actiondesc += "C"; // } else if (data.prop_state == LibSvnClient.NotifyState.Merged) { // actiondesc += "G"; // } // actiondesc += " {0}"; -// actiondesc = string.Format (actiondesc, file); */ +// actiondesc = string.Format (actiondesc, file); // actiondesc = string.Format (GettextCatalog.GetString ("Exists {0}"), file); // break; case LibSvnClient.NotifyAction.Restore: @@ -1430,12 +1448,8 @@ namespace MonoDevelop.VersionControl.Subversion.Unix lockFileList.Add (file); } - internal string GetDirectoryDotSvnInternal (FilePath path, out bool pre_1_7) + internal string GetDirectoryDotSvnInternal (FilePath path) { - pre_1_7 = this.pre_1_7; - if (pre_1_7) - return ""; - IntPtr result; IntPtr scratch = newpool (pool); var localpool = TryStartOperation (null); @@ -1448,11 +1462,10 @@ namespace MonoDevelop.VersionControl.Subversion.Unix switch (e.ErrorCode) { // SVN_ERR_WC_NOT_DIRECTORY case 155007: - // SVN_ERR_WC_NOT_FILE + // SVN_ERR_WC_NOT_FILE case 155008: return ""; } - throw; } return Marshal.PtrToStringAnsi (result); @@ -1462,9 +1475,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix TryEndOperation (); } } - + public class StatusCollector { - ArrayList statuses; + readonly ArrayList statuses; public LibSvnClient.svn_wc_status_func2_t Func { get; private set; @@ -1491,9 +1504,9 @@ namespace MonoDevelop.VersionControl.Subversion.Unix { static readonly DateTime Epoch = new DateTime (1970, 1, 1); - List<SvnRevision> logs; - SubversionRepository repo; - IntPtr ctx; + readonly List<SvnRevision> logs; + readonly SubversionRepository repo; + readonly IntPtr ctx; public LibSvnClient.svn_log_message_receiver_t Func { get; private set; @@ -1555,7 +1568,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix } public class StreamCollector { - Stream buf; + readonly Stream buf; public LibSvnClient.svn_readwrite_fn_t Func { get; private set; @@ -1585,7 +1598,7 @@ namespace MonoDevelop.VersionControl.Subversion.Unix /// </summary> private class AnnotationCollector { - Annotation[] annotations; + readonly Annotation[] annotations; public LibSvnClient.svn_client_blame_receiver_t Func { get; private set; } diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion.addin.xml b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion.addin.xml index 3e6b624e70..fbc00a58e3 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion.addin.xml +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion.addin.xml @@ -14,24 +14,4 @@ <Addin id="Ide" version="4.1.7"/>
<Addin id="VersionControl" version="4.1.7"/>
</Dependencies>
-
- <Extension path = "/MonoDevelop/Ide/Commands/VersionControl">
- <Command id = "MonoDevelop.VersionControl.Subversion.Commands.Resolve"
- _label = "Resolve"
- description = "Resolve conflicts on working copy files or directories."/>
- </Extension>
-
- <Extension path = "/MonoDevelop/Ide/Pads/ProjectPad">
- <NodeBuilder class = "MonoDevelop.VersionControl.Subversion.SubversionNodeExtension"/>
- </Extension>
-
- <Extension path = "/MonoDevelop/Ide/ContextMenu/ProjectPad/VersionControl">
- <Condition id="ItemType" value="IFileItem|IFolderItem">
- <CommandItem id = "MonoDevelop.VersionControl.Subversion.Commands.Resolve" insertafter="MonoDevelop.VersionControl.Commands.Revert" />
- </Condition>
- </Extension>
-
- <Extension path = "/MonoDevelop/VersionControl/StatusViewCommands">
- <CommandItem id = "MonoDevelop.VersionControl.Subversion.Commands.Resolve" type="MonoDevelop.VersionControl.Subversion.SubversionCommandHandler"/>
- </Extension>
</Addin>
diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion.csproj b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion.csproj index 337fc473cd..c9761420f4 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion.csproj +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion.csproj @@ -98,8 +98,6 @@ <Compile Include="gtk-gui\MonoDevelop.VersionControl.Subversion.Gui.ClientCertificatePasswordDialog.cs" /> <Compile Include="gtk-gui\MonoDevelop.VersionControl.Subversion.Gui.SslServerTrustDialog.cs" /> <Compile Include="gtk-gui\MonoDevelop.VersionControl.Subversion.Gui.UserPasswordDialog.cs" /> - <Compile Include="MonoDevelop.VersionControl.Subversion\SubversionNodeExtension.cs" /> - <Compile Include="MonoDevelop.VersionControl.Subversion\Commands.cs" /> <Compile Include="AssemblyInfo.cs" /> <Compile Include="MonoDevelop.VersionControl.Subversion\SvnRevision.cs" /> </ItemGroup> diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionNodeExtension.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionNodeExtension.cs deleted file mode 100644 index b31938e789..0000000000 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionNodeExtension.cs +++ /dev/null @@ -1,94 +0,0 @@ -// SubversionNodeExtension.cs -// -// Author: -// Lluis Sanchez Gual <lluis@novell.com> -// -// Copyright (c) 2008 Novell, Inc (http://www.novell.com) -// -// 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;
- -using MonoDevelop.Core;
-using MonoDevelop.Core.ProgressMonitoring;
-
-using MonoDevelop.Ide.Gui;
-using MonoDevelop.Ide.Gui.Pads;
-using MonoDevelop.Ide.Gui.Pads.ProjectPad;
-using MonoDevelop.Projects;
-using MonoDevelop.Components.Commands;
-using MonoDevelop.Ide.Gui.Components; - -namespace MonoDevelop.VersionControl.Subversion -{ - public class SubversionNodeExtension: NodeBuilderExtension - { - public override bool CanBuildNode (Type dataType) - {
- //Console.Error.WriteLine(dataType);
- return typeof(ProjectFile).IsAssignableFrom (dataType)
- || typeof(SystemFile).IsAssignableFrom (dataType)
- || typeof(ProjectFolder).IsAssignableFrom (dataType)
- || typeof(IWorkspaceObject).IsAssignableFrom (dataType);
- } -
- public override Type CommandHandlerType {
- get { return typeof(SubversionCommandHandler); }
- } - } - - class SubversionCommandHandler : VersionControlCommandHandler - { - [CommandHandler (Commands.Resolve)]
- protected void OnResolve() - { - foreach (VersionControlItemList items in GetItems ().SplitByRepository ()) {
- FilePath[] files = new FilePath[items.Count]; - for (int n=0; n<files.Length; n++) - files [n] = items [n].Path; - ((SubversionRepository)items[0].Repository).Resolve (files, true, new NullProgressMonitor ()); - } - }
-
- [CommandUpdateHandler (Commands.Resolve)]
- protected void UpdateResolve (CommandInfo item) - { - foreach (VersionControlItem vit in GetItems (false)) { - if (!(vit.Repository is SubversionRepository)) { - item.Visible = false; - return; - } -
- if (vit.IsDirectory) { - item.Visible = false; - return; - } - - VersionInfo vi = vit.Repository.GetVersionInfo (vit.Path); - if (vi != null && (vi.Status & VersionStatus.Conflicted) == 0) { - item.Visible = false; - return; - } - } - }
- }
-} diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionRepository.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionRepository.cs index b4921f802a..1a3c18c83f 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionRepository.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionRepository.cs @@ -68,9 +68,9 @@ namespace MonoDevelop.VersionControl.Subversion return GetVersionInfo (sourcefile, VersionInfoQueryFlags.IgnoreCache).IsVersioned;
}
- public override string GetBaseText (FilePath sourcefile)
+ public override string GetBaseText (FilePath localFile)
{
- return Svn.GetTextBase (sourcefile);
+ return Svn.GetTextBase (localFile);
}
protected override string OnGetTextAtRevision (FilePath repositoryPath, Revision revision)
@@ -78,9 +78,9 @@ namespace MonoDevelop.VersionControl.Subversion return Svn.GetTextAtRevision (repositoryPath, revision, RootPath);
}
- protected override Revision[] OnGetHistory (FilePath sourcefile, Revision since)
+ protected override Revision[] OnGetHistory (FilePath localFile, Revision since)
{
- return Svn.GetHistory (this, sourcefile, since);
+ return Svn.GetHistory (this, localFile, since);
}
protected override RevisionPath[] OnGetRevisionChanges (Revision revision)
@@ -96,9 +96,9 @@ namespace MonoDevelop.VersionControl.Subversion yield return Svn.GetVersionInfo (this, p, getRemoteStatus);
}
- protected override VersionInfo[] OnGetDirectoryVersionInfo (FilePath sourcepath, bool getRemoteStatus, bool recursive)
+ protected override VersionInfo[] OnGetDirectoryVersionInfo (FilePath localDirectory, bool getRemoteStatus, bool recursive)
{
- return Svn.GetDirectoryVersionInfo (this, sourcepath, getRemoteStatus, recursive);
+ return Svn.GetDirectoryVersionInfo (this, localDirectory, getRemoteStatus, recursive);
}
protected override VersionControlOperation GetSupportedOperations (VersionInfo vinfo)
@@ -138,7 +138,7 @@ namespace MonoDevelop.VersionControl.Subversion protected override Repository OnPublish (string serverPath, FilePath localPath, FilePath[] files, string message, IProgressMonitor monitor)
{
string url = Url;
- if (!serverPath.StartsWith ("/") && !url.EndsWith ("/"))
+ if (!serverPath.StartsWith ("/", StringComparison.Ordinal) && !url.EndsWith ("/", StringComparison.Ordinal))
url += "/";
url += serverPath;
@@ -171,9 +171,9 @@ namespace MonoDevelop.VersionControl.Subversion }
}
- protected override void OnUpdate (FilePath[] paths, bool recurse, IProgressMonitor monitor)
+ protected override void OnUpdate (FilePath[] localPaths, bool recurse, IProgressMonitor monitor)
{
- foreach (string path in paths)
+ foreach (string path in localPaths)
Svn.Update (path, recurse, monitor);
}
@@ -190,18 +190,9 @@ namespace MonoDevelop.VersionControl.Subversion Svn.Mkdir (paths, message, monitor);
}
- protected override void OnCheckout (FilePath path, Revision rev, bool recurse, IProgressMonitor monitor)
+ protected override void OnCheckout (FilePath targetLocalPath, Revision rev, bool recurse, IProgressMonitor monitor)
{
- Svn.Checkout (this.Url, path, rev, recurse, monitor);
- }
-
- public void Resolve (FilePath[] localPaths, bool recurse, IProgressMonitor monitor)
- {
- Svn.Resolve (localPaths, recurse, monitor);
- FileUpdateEventArgs args = new FileUpdateEventArgs ();
- foreach (var path in localPaths)
- args.Add (new FileUpdateEventInfo (this, path, Directory.Exists (path)));
- VersionControlService.NotifyFileStatusChanged (args);
+ Svn.Checkout (this.Url, targetLocalPath, rev, recurse, monitor);
}
protected override void OnRevert (FilePath[] localPaths, bool recurse, IProgressMonitor monitor)
@@ -225,9 +216,9 @@ namespace MonoDevelop.VersionControl.Subversion Svn.RevertToRevision (localPath, revision, monitor);
}
- protected override void OnAdd (FilePath[] paths, bool recurse, IProgressMonitor monitor)
+ protected override void OnAdd (FilePath[] localPaths, bool recurse, IProgressMonitor monitor)
{
- foreach (FilePath path in paths) {
+ foreach (FilePath path in localPaths) {
if (IsVersioned (path) && File.Exists (path) && !Directory.Exists (path)) {
if (RootPath.IsNull)
throw new UserException (GettextCatalog.GetString ("Project publishing failed. There is a stale .svn folder in the path '{0}'", path.ParentDirectory));
@@ -298,48 +289,48 @@ namespace MonoDevelop.VersionControl.Subversion return (srcRepository is SubversionRepository) && ((SubversionRepository)srcRepository).Root == Root;
}
- protected override void OnMoveFile (FilePath srcPath, FilePath destPath, bool force, IProgressMonitor monitor)
+ protected override void OnMoveFile (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor)
{
bool destIsVersioned = false;
- if (File.Exists (destPath))
+ if (File.Exists (localDestPath))
throw new InvalidOperationException ("Cannot move file. Destination file already exist.");
- if (IsVersioned (destPath)) {
+ if (IsVersioned (localDestPath)) {
// Revert to the original status
- Revert (destPath, false, monitor);
- if (File.Exists (destPath))
- File.Delete (destPath);
+ Revert (localDestPath, false, monitor);
+ if (File.Exists (localDestPath))
+ File.Delete (localDestPath);
destIsVersioned = true;
}
- VersionInfo srcInfo = GetVersionInfo (srcPath, VersionInfoQueryFlags.IgnoreCache);
+ VersionInfo srcInfo = GetVersionInfo (localSrcPath, VersionInfoQueryFlags.IgnoreCache);
if (srcInfo != null && srcInfo.HasLocalChange (VersionStatus.ScheduledAdd)) {
// If the file is scheduled to add, cancel it, move the file, and schedule to add again
- Revert (srcPath, false, monitor);
+ Revert (localSrcPath, false, monitor);
if (!destIsVersioned)
- MakeDirVersioned (Path.GetDirectoryName (destPath), monitor);
- base.OnMoveFile (srcPath, destPath, force, monitor);
+ MakeDirVersioned (Path.GetDirectoryName (localDestPath), monitor);
+ base.OnMoveFile (localSrcPath, localDestPath, force, monitor);
if (!destIsVersioned)
- Add (destPath, false, monitor);
+ Add (localDestPath, false, monitor);
} else {
- if (!destIsVersioned && IsVersioned (srcPath)) {
- MakeDirVersioned (Path.GetDirectoryName (destPath), monitor);
- Svn.Move (srcPath, destPath, force, monitor);
+ if (!destIsVersioned && IsVersioned (localSrcPath)) {
+ MakeDirVersioned (Path.GetDirectoryName (localDestPath), monitor);
+ Svn.Move (localSrcPath, localDestPath, force, monitor);
} else
- base.OnMoveFile (srcPath, destPath, force, monitor);
+ base.OnMoveFile (localSrcPath, localDestPath, force, monitor);
}
}
- protected override void OnMoveDirectory (FilePath srcPath, FilePath destPath, bool force, IProgressMonitor monitor)
+ protected override void OnMoveDirectory (FilePath localSrcPath, FilePath localDestPath, bool force, IProgressMonitor monitor)
{
- if (IsVersioned (destPath))
+ if (IsVersioned (localDestPath))
{
- VersionInfo vinfo = GetVersionInfo (destPath, VersionInfoQueryFlags.IgnoreCache);
- if (!vinfo.HasLocalChange (VersionStatus.ScheduledDelete) && Directory.Exists (destPath))
+ VersionInfo vinfo = GetVersionInfo (localDestPath, VersionInfoQueryFlags.IgnoreCache);
+ if (!vinfo.HasLocalChange (VersionStatus.ScheduledDelete) && Directory.Exists (localDestPath))
throw new InvalidOperationException ("Cannot move directory. Destination directory already exist.");
- srcPath = srcPath.FullPath;
+ localSrcPath = localSrcPath.FullPath;
// The target directory does not exist, but it is versioned. It may be because
// it is scheduled to delete, or maybe it has been physicaly deleted. In any
@@ -347,22 +338,22 @@ namespace MonoDevelop.VersionControl.Subversion // Revert the old directory, so we can see which files were there so
// we can delete or replace them
- Revert (destPath, true, monitor);
+ Revert (localDestPath, true, monitor);
// Get the list of files in the directory to be replaced
ArrayList oldFiles = new ArrayList ();
- GetDirectoryFiles (destPath, oldFiles);
+ GetDirectoryFiles (localDestPath, oldFiles);
// Get the list of files to move
ArrayList newFiles = new ArrayList ();
- GetDirectoryFiles (srcPath, newFiles);
+ GetDirectoryFiles (localSrcPath, newFiles);
// Move all new files to the new destination
Hashtable copiedFiles = new Hashtable ();
Hashtable copiedFolders = new Hashtable ();
foreach (string file in newFiles) {
string src = Path.GetFullPath (file);
- string dst = Path.Combine (destPath, src.Substring (((string)srcPath).Length + 1));
+ string dst = Path.Combine (localDestPath, src.Substring (((string)localSrcPath).Length + 1));
if (File.Exists (dst))
File.Delete (dst);
@@ -399,25 +390,25 @@ namespace MonoDevelop.VersionControl.Subversion }
// Delete the source directory
- DeleteDirectory (srcPath, true, monitor, false);
+ DeleteDirectory (localSrcPath, true, monitor, false);
}
else {
- if (Directory.Exists (destPath))
+ if (Directory.Exists (localDestPath))
throw new InvalidOperationException ("Cannot move directory. Destination directory already exist.");
- VersionInfo srcInfo = GetVersionInfo (srcPath, VersionInfoQueryFlags.IgnoreCache);
+ VersionInfo srcInfo = GetVersionInfo (localSrcPath, VersionInfoQueryFlags.IgnoreCache);
if (srcInfo != null && srcInfo.HasLocalChange (VersionStatus.ScheduledAdd)) {
// If the directory is scheduled to add, cancel it, move the directory, and schedule to add it again
- MakeDirVersioned (Path.GetDirectoryName (destPath), monitor);
- Revert (srcPath, true, monitor);
- base.OnMoveDirectory (srcPath, destPath, force, monitor);
- Add (destPath, true, monitor);
+ MakeDirVersioned (Path.GetDirectoryName (localDestPath), monitor);
+ Revert (localSrcPath, true, monitor);
+ base.OnMoveDirectory (localSrcPath, localDestPath, force, monitor);
+ Add (localDestPath, true, monitor);
} else {
- if (IsVersioned (srcPath)) {
- MakeDirVersioned (Path.GetDirectoryName (destPath), monitor);
- Svn.Move (srcPath, destPath, force, monitor);
+ if (IsVersioned (localSrcPath)) {
+ MakeDirVersioned (Path.GetDirectoryName (localDestPath), monitor);
+ Svn.Move (localSrcPath, localDestPath, force, monitor);
} else
- base.OnMoveDirectory (srcPath, destPath, force, monitor);
+ base.OnMoveDirectory (localSrcPath, localDestPath, force, monitor);
}
}
}
@@ -450,13 +441,13 @@ namespace MonoDevelop.VersionControl.Subversion }
[Obsolete ("Use the overload with keepLocal parameter")]
- protected override void OnDeleteFiles (FilePath[] paths, bool force, IProgressMonitor monitor)
+ protected override void OnDeleteFiles (FilePath[] localPaths, bool force, IProgressMonitor monitor)
{
}
- protected override void OnDeleteFiles (FilePath[] paths, bool force, IProgressMonitor monitor, bool keepLocal)
+ protected override void OnDeleteFiles (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal)
{
- foreach (string path in paths) {
+ foreach (string path in localPaths) {
if (IsVersioned (path)) {
string newPath = String.Empty;
if (keepLocal) {
@@ -483,13 +474,13 @@ namespace MonoDevelop.VersionControl.Subversion }
[Obsolete ("Use the overload with keepLocal parameter")]
- protected override void OnDeleteDirectories (FilePath[] paths, bool force, IProgressMonitor monitor)
+ protected override void OnDeleteDirectories (FilePath[] localPaths, bool force, IProgressMonitor monitor)
{
}
- protected override void OnDeleteDirectories (FilePath[] paths, bool force, IProgressMonitor monitor, bool keepLocal)
+ protected override void OnDeleteDirectories (FilePath[] localPaths, bool force, IProgressMonitor monitor, bool keepLocal)
{
- foreach (string path in paths) {
+ foreach (string path in localPaths) {
if (IsVersioned (path)) {
string newPath = String.Empty;
if (keepLocal) {
@@ -547,12 +538,12 @@ namespace MonoDevelop.VersionControl.Subversion }
}
- public override Annotation[] GetAnnotations (FilePath localPath)
+ public override Annotation[] GetAnnotations (FilePath repositoryPath)
{
- List<Annotation> annotations = new List<Annotation> (Svn.GetAnnotations (this, localPath, SvnRevision.First, SvnRevision.Base));
+ List<Annotation> annotations = new List<Annotation> (Svn.GetAnnotations (this, repositoryPath, SvnRevision.First, SvnRevision.Base));
Annotation nextRev = new Annotation (GettextCatalog.GetString ("working copy"), "<uncommitted>", DateTime.MinValue);
- var baseDocument = new Mono.TextEditor.TextDocument (GetBaseText (localPath));
- var workingDocument = new Mono.TextEditor.TextDocument (File.ReadAllText (localPath));
+ var baseDocument = new Mono.TextEditor.TextDocument (GetBaseText (repositoryPath));
+ var workingDocument = new Mono.TextEditor.TextDocument (File.ReadAllText (repositoryPath));
// "SubversionException: blame of the WORKING revision is not supported"
foreach (var hunk in baseDocument.Diff (workingDocument)) {
@@ -591,14 +582,14 @@ namespace MonoDevelop.VersionControl.Subversion return patch.ToString ();
}
- protected override void OnIgnore (FilePath[] paths)
+ protected override void OnIgnore (FilePath[] localPath)
{
- Svn.Ignore (paths);
+ Svn.Ignore (localPath);
}
- protected override void OnUnignore (FilePath[] paths)
+ protected override void OnUnignore (FilePath[] localPath)
{
- Svn.Unignore (paths);
+ Svn.Unignore (localPath);
}
}
}
diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionVersionControl.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionVersionControl.cs index 5deddc7616..16a0aa90a4 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionVersionControl.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/SubversionVersionControl.cs @@ -173,14 +173,6 @@ namespace MonoDevelop.VersionControl.Subversion public abstract void Revert (FilePath[] paths, bool recurse, IProgressMonitor monitor);
- public virtual void Resolve (FilePath[] paths, bool recurse, IProgressMonitor monitor) - { - foreach (string path in paths) - Resolve (path, recurse, monitor); - }
-
- public abstract void Resolve (FilePath path, bool recurse, IProgressMonitor monitor);
-
public abstract void RevertRevision (FilePath path, Revision revision, IProgressMonitor monitor);
public abstract void RevertToRevision (FilePath path, Revision revision, IProgressMonitor monitor);
diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/StatusView.cs b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/StatusView.cs index bae567c0f9..82cf6e29b5 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/StatusView.cs +++ b/main/src/addins/VersionControl/MonoDevelop.VersionControl/MonoDevelop.VersionControl.Views/StatusView.cs @@ -928,7 +928,10 @@ namespace MonoDevelop.VersionControl.Views TreeIter oldStatusIter = TreeIter.Zero; // Locate the file in the status object list - for (oldStatusIndex=0; oldStatusIndex<statuses.Count; oldStatusIndex++) { + if (statuses == null) + return false; + + for (oldStatusIndex = 0; oldStatusIndex < statuses.Count; oldStatusIndex++) { if (statuses [oldStatusIndex].LocalPath == args.FilePath) { found = true; break; diff --git a/main/src/addins/VersionControl/Subversion.Win32/SvnSharpClient.cs b/main/src/addins/VersionControl/Subversion.Win32/SvnSharpClient.cs index 7896ceacf9..171958f098 100644 --- a/main/src/addins/VersionControl/Subversion.Win32/SvnSharpClient.cs +++ b/main/src/addins/VersionControl/Subversion.Win32/SvnSharpClient.cs @@ -16,8 +16,8 @@ namespace SubversionAddinWindows public class SvnSharpClient: SubversionVersionControl
{
static bool errorShown;
- static bool installError;
- static SvnClient client;
+ static readonly bool installError;
+ static readonly SvnClient client;
static SvnSharpClient ()
{
@@ -81,14 +81,14 @@ namespace SubversionAddinWindows IProgressMonitor updateMonitor;
ProgressData progressData;
- public override string GetTextBase (string file)
+ public override string GetTextBase (string sourcefile)
{
MemoryStream data = new MemoryStream ();
try {
// This outputs the contents of the base revision
// of a file to a stream.
- client.Write (new SvnPathTarget (file), data);
- return TextFile.ReadFile (file, data).Text;
+ client.Write (new SvnPathTarget (sourcefile), data);
+ return TextFile.ReadFile (sourcefile, data).Text;
} catch (SvnIllegalTargetException e) {
// This occurs when we don't have a base file for
// the target file. We have no way of knowing if
@@ -363,15 +363,6 @@ namespace SubversionAddinWindows }
}
- public override void Resolve (FilePath path, bool recurse, IProgressMonitor monitor)
- {
- SvnResolveArgs args = new SvnResolveArgs ();
- BindMonitor (args, monitor);
- args.Depth = recurse ? SvnDepth.Infinity : SvnDepth.Children;
- lock (client)
- client.Resolve (path, SvnAccept.MineFull, args);
- }
-
public override void Revert (FilePath[] paths, bool recurse, IProgressMonitor monitor)
{
SvnRevertArgs args = new SvnRevertArgs ();
@@ -648,7 +639,7 @@ namespace SubversionAddinWindows return;
data.LogTimer.Interval = 1000;
- data.LogTimer.Elapsed += delegate (object sender, ElapsedEventArgs eea) {
+ data.LogTimer.Elapsed += delegate {
data.Seconds += 1;
monitor.Log.WriteLine ("{0} bytes in {1} seconds", data.Bytes, data.Seconds);
};
diff --git a/main/src/addins/WindowsPlatform/Dialogs/OpenFileDialogEx.cs b/main/src/addins/WindowsPlatform/Dialogs/OpenFileDialogEx.cs index d59e6cca56..6ca8fc0dda 100644 --- a/main/src/addins/WindowsPlatform/Dialogs/OpenFileDialogEx.cs +++ b/main/src/addins/WindowsPlatform/Dialogs/OpenFileDialogEx.cs @@ -670,18 +670,3 @@ namespace CustomControls.Controls }
#endregion
}
-
-[AttributeUsage(AttributeTargets.Class |
- AttributeTargets.Enum |
- AttributeTargets.Interface |
- AttributeTargets.Struct,
- AllowMultiple = true)]
-[Author("Franco, Gustavo")]
-internal class AuthorAttribute : Attribute
-{
- #region Constructors
- public AuthorAttribute(string authorName)
- {
- }
- #endregion
-}
diff --git a/main/src/addins/WindowsPlatform/Enums.cs b/main/src/addins/WindowsPlatform/Enums.cs index 579f51b13f..489c9def44 100644 --- a/main/src/addins/WindowsPlatform/Enums.cs +++ b/main/src/addins/WindowsPlatform/Enums.cs @@ -259,6 +259,7 @@ namespace CustomControls.OS #region Window Extended Styles
[Author("Franco, Gustavo")]
+ [Flags]
public enum WindowExStyles
{
WS_EX_DLGMODALFRAME = 0x00000001,
@@ -549,6 +550,7 @@ namespace CustomControls.OS #region SetWindowPosFlags
[Author("Franco, Gustavo")]
+ [Flags]
public enum SetWindowPosFlags
{
SWP_NOSIZE = 0x0001,
diff --git a/main/src/addins/WindowsPlatform/Win32.cs b/main/src/addins/WindowsPlatform/Win32.cs index 4473829e9c..ccc311b5f0 100644 --- a/main/src/addins/WindowsPlatform/Win32.cs +++ b/main/src/addins/WindowsPlatform/Win32.cs @@ -32,6 +32,8 @@ namespace CustomControls.OS public const uint SHGFI_SMALLICON = 0x1; // 'Small icon
public const uint SHGFI_ICONLOCATION = 0x1000;
public const uint SHGFI_TYPENAME = 0x400;
+ public const uint SHGFI_USEFILEATTRIBUTES = 0x10;
+ public const uint FILE_ATTRIBUTES_NORMAL = 0x80;
#region Delegates
public delegate bool EnumWindowsCallBack(IntPtr hWnd, int lParam);
@@ -88,8 +90,25 @@ namespace CustomControls.OS public static extern bool GetWindowRect(IntPtr hwnd, ref RECT rect);
[DllImport("user32.dll")]
public static extern bool GetClientRect(IntPtr hwnd, ref RECT rect);
- [DllImport("shell32.dll")]
- public static extern IntPtr SHGetFileInfo(string pszPath, uint dwFileAttributes, ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
+ [DllImport("user32.dll")]
+ public static extern bool DestroyIcon([In] IntPtr hIcon);
+ [DllImport("shell32.dll", CharSet = CharSet.Unicode)]
+ public static extern IntPtr SHGetFileInfoW([In] string pszPath, uint dwFileAttributes, [In, Out] ref SHFILEINFO psfi, uint cbSizeFileInfo, uint uFlags);
#endregion
}
+
+ [AttributeUsage(AttributeTargets.Class |
+ AttributeTargets.Enum |
+ AttributeTargets.Interface |
+ AttributeTargets.Struct,
+ AllowMultiple = true)]
+ [Author("Franco, Gustavo")]
+ internal class AuthorAttribute : Attribute
+ {
+ #region Constructors
+ public AuthorAttribute(string authorName)
+ {
+ }
+ #endregion
+ }
}
diff --git a/main/src/addins/WindowsPlatform/WindowsPlatform.cs b/main/src/addins/WindowsPlatform/WindowsPlatform.cs index 6ff77f87d7..75b72d2f76 100644 --- a/main/src/addins/WindowsPlatform/WindowsPlatform.cs +++ b/main/src/addins/WindowsPlatform/WindowsPlatform.cs @@ -95,20 +95,25 @@ namespace MonoDevelop.Platform } Dictionary<string, Gdk.Pixbuf> icons = new Dictionary<string, Gdk.Pixbuf> (); - + + // http://msdn.microsoft.com/en-us/library/windows/desktop/bb762179(v=vs.85).aspx + // FIXME: You should call this function from a background thread. Failure to do so could cause the UI to stop responding. protected override Gdk.Pixbuf OnGetPixbufForFile (string filename, Gtk.IconSize size) { SHFILEINFO shinfo = new SHFILEINFO(); - Win32.SHGetFileInfo (filename, 0, ref shinfo, (uint) Marshal.SizeOf (shinfo), Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON | Win32.SHGFI_ICONLOCATION | Win32.SHGFI_TYPENAME); - if (shinfo.iIcon == IntPtr.Zero) - return null; - string key = shinfo.iIcon.ToString () + " - " + shinfo.szDisplayName; + Win32.SHGetFileInfoW (filename, Win32.FILE_ATTRIBUTES_NORMAL, ref shinfo, (uint)Marshal.SizeOf (shinfo), Win32.SHGFI_USEFILEATTRIBUTES | Win32.SHGFI_ICON | Win32.SHGFI_SMALLICON | Win32.SHGFI_ICONLOCATION | Win32.SHGFI_TYPENAME);
+ if (shinfo.iIcon == 0) {
+ Win32.DestroyIcon (shinfo.hIcon);
+ return null;
+ } + string key = shinfo.iIcon + " - " + shinfo.szDisplayName; Gdk.Pixbuf pix; if (!icons.TryGetValue (key, out pix)) { var icon = Icon.FromHandle (shinfo.hIcon); pix = CreateFromResource (icon.ToBitmap ()); icons[key] = pix; - } + }
+ Win32.DestroyIcon (shinfo.hIcon); return pix; } diff --git a/main/src/addins/WindowsPlatform/structs.cs b/main/src/addins/WindowsPlatform/structs.cs index addebd3897..b39f00b566 100644 --- a/main/src/addins/WindowsPlatform/structs.cs +++ b/main/src/addins/WindowsPlatform/structs.cs @@ -164,11 +164,11 @@ namespace CustomControls.OS }
#endregion
- [StructLayout(LayoutKind.Sequential)]
+ [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct SHFILEINFO
{
public IntPtr hIcon;
- public IntPtr iIcon;
+ public int iIcon;
public uint dwAttributes;
[MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)]
public string szDisplayName;
diff --git a/main/src/core/Mono.Texteditor/Mono.TextEditor.Vi/ViMode.cs b/main/src/core/Mono.Texteditor/Mono.TextEditor.Vi/ViMode.cs index 935c7741fd..9c31c17ef7 100644 --- a/main/src/core/Mono.Texteditor/Mono.TextEditor.Vi/ViMode.cs +++ b/main/src/core/Mono.Texteditor/Mono.TextEditor.Vi/ViMode.cs @@ -191,7 +191,7 @@ namespace Mono.TextEditor.Vi void CheckVisualMode () { - if (CurState == ViEditMode.State.Visual || CurState == ViEditMode.State.Visual) { + if (CurState == ViEditMode.State.Visual || CurState == ViEditMode.State.VisualLine) { if (!Data.IsSomethingSelected) CurState = ViEditMode.State.Normal; } else { diff --git a/main/src/core/Mono.Texteditor/Mono.TextEditor/Gui/GtkWorkarounds.cs b/main/src/core/Mono.Texteditor/Mono.TextEditor/Gui/GtkWorkarounds.cs index e171ce405c..881a5443cd 100644 --- a/main/src/core/Mono.Texteditor/Mono.TextEditor/Gui/GtkWorkarounds.cs +++ b/main/src/core/Mono.Texteditor/Mono.TextEditor/Gui/GtkWorkarounds.cs @@ -64,6 +64,9 @@ namespace Mono.TextEditor [DllImport (LIBOBJC, EntryPoint = "objc_msgSend")] static extern ulong objc_msgSend_NSUInt64 (IntPtr klass, IntPtr selector); + + [DllImport (LIBOBJC, EntryPoint = "objc_msgSend")] + static extern void objc_msgSend_NSInt64_NSInt32 (IntPtr klass, IntPtr selector, int arg); [DllImport (LIBOBJC, EntryPoint = "objc_msgSend_stret")] static extern void objc_msgSend_CGRect32 (out CGRect32 rect, IntPtr klass, IntPtr selector); @@ -94,7 +97,7 @@ namespace Mono.TextEditor static IntPtr cls_NSScreen; static IntPtr sel_screens, sel_objectEnumerator, sel_nextObject, sel_frame, sel_visibleFrame, - sel_requestUserAttention, sel_setHasShadow, sel_invalidateShadow; + sel_requestUserAttention, sel_setHasShadow, sel_invalidateShadow, sel_terminate; static IntPtr sharedApp; static IntPtr cls_NSEvent; static IntPtr sel_modifierFlags; @@ -159,6 +162,7 @@ namespace Mono.TextEditor sel_modifierFlags = sel_registerName ("modifierFlags"); sel_setHasShadow = sel_registerName ("setHasShadow:"); sel_invalidateShadow = sel_registerName ("invalidateShadow"); + sel_terminate = sel_registerName ("terminate:"); sharedApp = objc_msgSend_IntPtr (objc_getClass ("NSApplication"), sel_registerName ("sharedApplication")); } @@ -231,6 +235,11 @@ namespace Mono.TextEditor } } + static void MacTerminate () + { + objc_msgSend_NSInt64_NSInt32 (sharedApp, sel_terminate, 0); + } + // Note: we can't reuse RectangleF because the layout is different... [StructLayout (LayoutKind.Sequential)] struct Rect { @@ -301,7 +310,13 @@ namespace Mono.TextEditor return new Gdk.Rectangle (x, y, width, height); } - + + public static void Terminate () + { + if (Platform.IsMac) + MacTerminate (); + } + public static Gdk.Rectangle GetUsableMonitorGeometry (this Gdk.Screen screen, int monitor) { if (Platform.IsWindows) diff --git a/main/src/core/Mono.Texteditor/Mono.TextEditor/Gui/TextViewMargin.cs b/main/src/core/Mono.Texteditor/Mono.TextEditor/Gui/TextViewMargin.cs index 9fa535119b..0f579fe239 100644 --- a/main/src/core/Mono.Texteditor/Mono.TextEditor/Gui/TextViewMargin.cs +++ b/main/src/core/Mono.Texteditor/Mono.TextEditor/Gui/TextViewMargin.cs @@ -2148,9 +2148,10 @@ namespace Mono.TextEditor previewWindow = null; return false; } - + if (textEditor == null || textEditor.GdkWindow == null) + return false; int ox = 0, oy = 0; - this.textEditor.GdkWindow.GetOrigin (out ox, out oy); + textEditor.GdkWindow.GetOrigin (out ox, out oy); ox += textEditor.Allocation.X; oy += textEditor.Allocation.Y; diff --git a/main/src/core/Mono.Texteditor/Mono.TextEditor/IIndentationTracker.cs b/main/src/core/Mono.Texteditor/Mono.TextEditor/IIndentationTracker.cs index 138c463782..1ffea9b4ff 100644 --- a/main/src/core/Mono.Texteditor/Mono.TextEditor/IIndentationTracker.cs +++ b/main/src/core/Mono.Texteditor/Mono.TextEditor/IIndentationTracker.cs @@ -23,7 +23,6 @@ // 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; namespace Mono.TextEditor { @@ -51,7 +50,7 @@ namespace Mono.TextEditor class DefaultIndentationTracker : IIndentationTracker { - TextDocument doc; + readonly TextDocument doc; public DefaultIndentationTracker (TextDocument doc) { @@ -60,18 +59,20 @@ namespace Mono.TextEditor public string GetIndentationString (int offset) { - DocumentLine line = doc.GetLineByOffset (offset); - if (line == null) - return ""; - return line.GetIndentation (doc); + var loc = doc.OffsetToLocation (offset); + return GetIndentationString (loc.Line, loc.Column); } public string GetIndentationString (int lineNumber, int column) { - DocumentLine line = doc.GetLine (lineNumber); - if (line == null) - return ""; - return line.GetIndentation (doc); + DocumentLine line = doc.GetLine (lineNumber - 1); + while (line != null) { + var indent = line.GetIndentation (doc); + if (indent.Length > 0) + return indent; + line = line.PreviousLine; + } + return ""; } public int GetVirtualIndentationColumn (int offset) diff --git a/main/src/core/Mono.Texteditor/Mono.TextEditor/ISearchEngine.cs b/main/src/core/Mono.Texteditor/Mono.TextEditor/ISearchEngine.cs index dcac15c40a..1cdc7646f8 100644 --- a/main/src/core/Mono.Texteditor/Mono.TextEditor/ISearchEngine.cs +++ b/main/src/core/Mono.Texteditor/Mono.TextEditor/ISearchEngine.cs @@ -35,39 +35,44 @@ namespace Mono.TextEditor get; set; } - + TextEditorData TextEditorData { get; set; } - + void CompilePattern (); - + bool IsValidPattern (string pattern, out string error); + bool IsMatchAt (int offset); + bool IsMatchAt (int offset, int length); - + SearchResult GetMatchAt (int offset); + SearchResult GetMatchAt (int offset, int length); - + SearchResult SearchForward (System.ComponentModel.BackgroundWorker worker, TextViewMargin.SearchWorkerArguments args, int fromOffset); + SearchResult SearchBackward (System.ComponentModel.BackgroundWorker worker, TextViewMargin.SearchWorkerArguments args, int fromOffset); - + SearchResult SearchForward (int fromOffset); + SearchResult SearchBackward (int fromOffset); - + void Replace (SearchResult result, string pattern); int ReplaceAll (string withPattern); - + ISearchEngine Clone (); } - + public abstract class AbstractSearchEngine : ISearchEngine { protected SearchRequest searchRequest; protected TextEditorData textEditorData; - + public TextEditorData TextEditorData { get { return textEditorData; @@ -76,7 +81,7 @@ namespace Mono.TextEditor textEditorData = value; } } - + public SearchRequest SearchRequest { get { return searchRequest; @@ -91,90 +96,73 @@ namespace Mono.TextEditor } } } - + void OnRequestChanged (object ob, EventArgs args) { if (searchRequest != null) CompilePattern (); } - + public bool IsMatchAt (int offset) { return GetMatchAt (offset) != null; } - + public bool IsMatchAt (int offset, int length) { return GetMatchAt (offset, length) != null; } - + public abstract void CompilePattern (); - + public abstract bool IsValidPattern (string pattern, out string error); + public abstract SearchResult GetMatchAt (int offset); + public abstract SearchResult GetMatchAt (int offset, int length); - + public abstract SearchResult SearchForward (System.ComponentModel.BackgroundWorker worker, TextViewMargin.SearchWorkerArguments args, int fromOffset); + public abstract SearchResult SearchBackward (System.ComponentModel.BackgroundWorker worker, TextViewMargin.SearchWorkerArguments args, int fromOffset); - + public SearchResult SearchForward (int fromOffset) { - return SearchForward (null, new TextViewMargin.SearchWorkerArguments () { Text = textEditorData.Text }, fromOffset); + return SearchForward (null, new TextViewMargin.SearchWorkerArguments { Text = textEditorData.Text }, fromOffset); } public SearchResult SearchBackward (int fromOffset) { - return SearchBackward (null, new TextViewMargin.SearchWorkerArguments () { Text = textEditorData.Text }, fromOffset); + return SearchBackward (null, new TextViewMargin.SearchWorkerArguments { Text = textEditorData.Text }, fromOffset); } + public abstract void Replace (SearchResult result, string pattern); - public virtual int ReplaceAll (string withPattern) - { - int result = 0; - using (var undo = textEditorData.OpenUndoGroup ()) { - int offset = 0; - if (!SearchRequest.SearchRegion.IsInvalid) - offset = SearchRequest.SearchRegion.Offset; - SearchResult searchResult; - var text = textEditorData.Text; - var args = new TextViewMargin.SearchWorkerArguments () { Text = text }; - while (true) { - searchResult = SearchForward (null, args, offset); - if (searchResult == null || searchResult.SearchWrapped) - break; - Replace (searchResult, withPattern); - offset = searchResult.EndOffset; - result++; - } - if (result > 0) - textEditorData.ClearSelection (); - } - return result; - } + public abstract int ReplaceAll (string withPattern); public virtual ISearchEngine Clone () { - ISearchEngine result = (ISearchEngine)MemberwiseClone (); + var result = (ISearchEngine)MemberwiseClone (); result.SearchRequest = searchRequest.Clone (); return result; } } - + public class BasicSearchEngine : AbstractSearchEngine { string compiledPattern = ""; + public override void CompilePattern () { if (searchRequest.SearchPattern != null) compiledPattern = searchRequest.CaseSensitive ? searchRequest.SearchPattern : searchRequest.SearchPattern.ToUpper (); } - + public override bool IsValidPattern (string pattern, out string error) { error = ""; return pattern != null; } - + public override SearchResult GetMatchAt (int offset, int length) { if (compiledPattern.Length == length) { @@ -184,22 +172,22 @@ namespace Mono.TextEditor } return null; } - + public override SearchResult GetMatchAt (int offset) { if (offset < 0) return null; - var doc = this.textEditorData.Document; - + var doc = textEditorData.Document; + if ((!string.IsNullOrEmpty (SearchRequest.SearchPattern)) && offset + searchRequest.SearchPattern.Length <= doc.TextLength && compiledPattern.Length > 0) { if (searchRequest.CaseSensitive) { for (int i = 0; i < compiledPattern.Length && offset + i < doc.TextLength; i++) { - if (doc.GetCharAt (offset + i) != compiledPattern [i]) + if (doc.GetCharAt (offset + i) != compiledPattern [i]) return null; } } else { for (int i = 0; i < compiledPattern.Length && offset + i < doc.TextLength; i++) { - if (System.Char.ToUpper (doc.GetCharAt (offset + i)) != compiledPattern [i]) + if (Char.ToUpper (doc.GetCharAt (offset + i)) != compiledPattern [i]) return null; } } @@ -211,7 +199,7 @@ namespace Mono.TextEditor } return null; } - + public override SearchResult SearchForward (System.ComponentModel.BackgroundWorker worker, TextViewMargin.SearchWorkerArguments args, int fromOffset) { if (!string.IsNullOrEmpty (SearchRequest.SearchPattern)) { @@ -226,7 +214,7 @@ namespace Mono.TextEditor } return null; } - + public override SearchResult SearchBackward (System.ComponentModel.BackgroundWorker worker, TextViewMargin.SearchWorkerArguments args, int fromOffset) { if (!string.IsNullOrEmpty (SearchRequest.SearchPattern)) { @@ -256,7 +244,7 @@ namespace Mono.TextEditor offset = SearchRequest.SearchRegion.Offset; SearchResult searchResult; var text = textEditorData.Text; - var args = new TextViewMargin.SearchWorkerArguments () { Text = text }; + var args = new TextViewMargin.SearchWorkerArguments { Text = text }; while (true) { searchResult = SearchForward (null, args, offset); if (searchResult == null || searchResult.SearchWrapped) @@ -274,7 +262,7 @@ namespace Mono.TextEditor } } else { char[] oldText = text.ToCharArray (); - char[] newText = new char[oldText.Length + searchResults.Count * (withPattern.Length - compiledPattern.Length)]; + var newText = new char[oldText.Length + searchResults.Count * (withPattern.Length - compiledPattern.Length)]; char[] pattern = withPattern.ToCharArray (); int curOffset = 0, destOffset = 0; foreach (var sr in searchResults) { @@ -294,11 +282,11 @@ namespace Mono.TextEditor return searchResults.Count; } } - + public class RegexSearchEngine : AbstractSearchEngine { - Regex regex = null; - + Regex regex; + public override void CompilePattern () { try { @@ -310,7 +298,7 @@ namespace Mono.TextEditor regex = null; } } - + public override bool IsValidPattern (string pattern, out string error) { error = ""; @@ -318,60 +306,58 @@ namespace Mono.TextEditor RegexOptions options = RegexOptions.Compiled; if (!searchRequest.CaseSensitive) options |= RegexOptions.IgnoreCase; - Regex r = new Regex (searchRequest.SearchPattern, options); + var r = new Regex (searchRequest.SearchPattern, options); return r != null; } catch (Exception e) { error = e.Message; return false; } } - + public override SearchResult GetMatchAt (int offset) { if (regex == null || String.IsNullOrEmpty (searchRequest.SearchPattern)) return null; - System.Text.RegularExpressions.Match match = regex.Match (this.textEditorData.Document.Text, offset); + var match = regex.Match (textEditorData.Document.Text, offset); if (match != null && match.Success && match.Index == offset) { return new SearchResult (offset, match.Length, false); } return null; } - + public override SearchResult GetMatchAt (int offset, int length) { if (regex == null || String.IsNullOrEmpty (searchRequest.SearchPattern)) return null; - System.Text.RegularExpressions.Match match = regex.Match (this.textEditorData.Document.Text, offset, length); + var match = regex.Match (textEditorData.Document.Text, offset, length); if (match != null && match.Success && match.Index == offset) { return new SearchResult (offset, match.Length, false); } return null; } - + public override SearchResult SearchForward (System.ComponentModel.BackgroundWorker worker, TextViewMargin.SearchWorkerArguments args, int fromOffset) { if (regex == null || String.IsNullOrEmpty (searchRequest.SearchPattern)) return null; - System.Text.RegularExpressions.Match match = regex.Match (args.Text, fromOffset); + var match = regex.Match (args.Text, fromOffset); if (match.Success) { - return new SearchResult (match.Index, - match.Length, false); + return new SearchResult (match.Index, match.Length, false); } match = regex.Match (args.Text, 0, fromOffset); if (match.Success) { - return new SearchResult (match.Index, - match.Length, true); + return new SearchResult (match.Index, match.Length, true); } return null; } - - public override SearchResult SearchBackward (System.ComponentModel.BackgroundWorker worker, TextViewMargin.SearchWorkerArguments args, int fromOffset) + + public override SearchResult SearchBackward (System.ComponentModel.BackgroundWorker worker, TextViewMargin.SearchWorkerArguments args, int fromOffset) { if (regex == null || String.IsNullOrEmpty (searchRequest.SearchPattern)) return null; - System.Text.RegularExpressions.Match found = null; - System.Text.RegularExpressions.Match last = null; - foreach (System.Text.RegularExpressions.Match match in regex.Matches (args.Text)) { + Match found = null; + Match last = null; + foreach (Match match in regex.Matches (args.Text)) { if (match.Index < fromOffset) { found = match; } @@ -382,19 +368,41 @@ namespace Mono.TextEditor found = last; wrapped = true; } - - if (found != null) { - return new SearchResult (found.Index, found.Length, wrapped); - } - return null; + + return found != null ? new SearchResult (found.Index, found.Length, wrapped) : null; } - + public override void Replace (SearchResult result, string pattern) { - string text = this.textEditorData.Document.GetTextAt (result.Segment); - this.textEditorData.Replace (result.Offset, result.Length, regex.Replace (text, pattern)); + string text = textEditorData.Document.GetTextAt (result.Segment); + textEditorData.Replace (result.Offset, result.Length, regex.Replace (text, pattern)); + } + + public override int ReplaceAll (string withPattern) + { + var searchResults = new List<SearchResult> (); + + int offset = 0; + if (!SearchRequest.SearchRegion.IsInvalid) + offset = SearchRequest.SearchRegion.Offset; + SearchResult searchResult; + var text = textEditorData.Text; + var args = new TextViewMargin.SearchWorkerArguments { Text = text }; + while (true) { + searchResult = SearchForward (null, args, offset); + if (searchResult == null || searchResult.SearchWrapped) + break; + searchResults.Add (searchResult); + offset = searchResult.EndOffset; + } + using (var undo = textEditorData.OpenUndoGroup ()) { + for (int i = searchResults.Count - 1; i >= 0; i--) { + Replace (searchResults [i], withPattern); + } + if (searchResults.Count > 0) + textEditorData.ClearSelection (); + } + return searchResults.Count; } - } - -} +}
\ No newline at end of file diff --git a/main/src/core/Mono.Texteditor/Mono.TextEditor/TextEditorData.cs b/main/src/core/Mono.Texteditor/Mono.TextEditor/TextEditorData.cs index 2e02a8af41..b4935eda68 100644 --- a/main/src/core/Mono.Texteditor/Mono.TextEditor/TextEditorData.cs +++ b/main/src/core/Mono.Texteditor/Mono.TextEditor/TextEditorData.cs @@ -190,6 +190,7 @@ namespace Mono.TextEditor HeightTree = new HeightTree (this); HeightTree.Rebuild (); + IndentationTracker = new DefaultIndentationTracker (document); } void HandleFoldTreeUpdated (object sender, EventArgs e) diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Core.Assemblies/SupportedFramework.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Core.Assemblies/SupportedFramework.cs index ace1955f28..28c1c14924 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Core.Assemblies/SupportedFramework.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Core.Assemblies/SupportedFramework.cs @@ -26,6 +26,7 @@ using System; using System.IO; using System.Xml; +using System.Collections.Generic; namespace MonoDevelop.Core.Assemblies { @@ -81,6 +82,14 @@ namespace MonoDevelop.Core.Assemblies public Version MaximumVersion { get; internal set; } + + public string MonoSpecificVersion { + get; internal set; + } + + public string MonoSpecificVersionDisplayName { + get; internal set; + } public TargetFramework TargetFramework { get; private set; @@ -127,6 +136,12 @@ namespace MonoDevelop.Core.Assemblies case "DisplayName": fx.DisplayName = reader.Value; break; + case "MonoSpecificVersion": + fx.MonoSpecificVersion = reader.Value; + break; + case "MonoSpecificVersionDisplayName": + fx.MonoSpecificVersionDisplayName = reader.Value; + break; } } } @@ -136,5 +151,48 @@ namespace MonoDevelop.Core.Assemblies return fx; } + + public override int GetHashCode () + { + return DisplayName != null ? DisplayName.GetHashCode () : 0; + } + + public override bool Equals (object obj) + { + var other = obj as SupportedFramework; + if (other == null) + return false; + + if (!string.Equals (DisplayName, other.DisplayName)) + return false; + if (!string.Equals (Identifier, other.Identifier)) + return false; + if (!string.Equals (Profile, other.Profile)) + return false; + if (!string.Equals (MonoSpecificVersion, other.MonoSpecificVersion)) + return false; + if (!string.Equals (MonoSpecificVersionDisplayName, other.MonoSpecificVersionDisplayName)) + return false; + if (!string.Equals (MinimumVersionDisplayName, other.MinimumVersionDisplayName)) + return false; + if (!MinimumVersion.Equals (other.MinimumVersion)) + return false; + if (!MaximumVersion.Equals (other.MaximumVersion)) + return false; + return true; + } + + public static IEqualityComparer<SupportedFramework> EqualityComparer = new _Comparer (); + + class _Comparer : IEqualityComparer<SupportedFramework> { + public bool Equals (SupportedFramework x, SupportedFramework y) + { + return x.Equals (y); + } + public int GetHashCode (SupportedFramework obj) + { + return obj.GetHashCode (); + } + } } } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Core.Assemblies/TargetFramework.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Core.Assemblies/TargetFramework.cs index e258cfc4fd..26ec34a81d 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Core.Assemblies/TargetFramework.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Core.Assemblies/TargetFramework.cs @@ -158,7 +158,7 @@ namespace MonoDevelop.Core.Assemblies return false; var prefix = pattern.Substring (0, star); - return profile.StartsWith (prefix); + return profile.StartsWith (prefix, StringComparison.Ordinal); } return profile == pattern; @@ -197,17 +197,6 @@ namespace MonoDevelop.Core.Assemblies return true; } - // FIXME: this is a hack for systems w/o Portable Class Library definitions - if (fx.Id.Identifier == TargetFrameworkMoniker.ID_PORTABLE) { - switch (id.Identifier) { - case TargetFrameworkMoniker.ID_NET_FRAMEWORK: - return new Version (fx.Id.Version).CompareTo (new Version (id.Version)) <= 0; - case TargetFrameworkMoniker.ID_MONOTOUCH: - case TargetFrameworkMoniker.ID_MONODROID: - return true; - } - } - return fx.Id.Identifier == id.Identifier && new Version (fx.Id.Version).CompareTo (new Version (id.Version)) <= 0; } diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Core/IconId.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Core/IconId.cs index 8b7dbd3b09..de1a0fe6d5 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Core/IconId.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Core/IconId.cs @@ -88,7 +88,7 @@ namespace MonoDevelop.Core public override bool Equals (object obj) { - if (obj == null && !(obj is IconId)) + if (!(obj is IconId)) return false; IconId fn = (IconId) obj; diff --git a/main/src/core/MonoDevelop.Core/MonoDevelop.Core/PropertyBag.cs b/main/src/core/MonoDevelop.Core/MonoDevelop.Core/PropertyBag.cs index f98a7f6a2e..453ef5ad2a 100644 --- a/main/src/core/MonoDevelop.Core/MonoDevelop.Core/PropertyBag.cs +++ b/main/src/core/MonoDevelop.Core/MonoDevelop.Core/PropertyBag.cs @@ -69,6 +69,7 @@ namespace MonoDevelop.Core if (val is DataNode) { val = Deserialize (name, (DataNode) val, typeof(T), ctx ?? context); properties [name] = val; + OnChanged (name); } return (T) val; } @@ -106,6 +107,7 @@ namespace MonoDevelop.Core if (properties == null) properties = new Dictionary<string,object> (); properties [name] = value; + OnChanged (name); } public bool RemoveValue<T> () @@ -115,7 +117,12 @@ namespace MonoDevelop.Core public bool RemoveValue (string name) { - return properties != null && properties.Remove (name); + if (properties != null && properties.Remove (name)) { + OnChanged (name); + return true; + } + + return false; } public bool HasValue<T> () @@ -127,6 +134,16 @@ namespace MonoDevelop.Core { return properties != null && properties.ContainsKey (name); } + + public event EventHandler<PropertyBagChangedEventArgs> Changed; + + void OnChanged (string name) + { + var handler = Changed; + + if (handler != null) + handler (this, new PropertyBagChangedEventArgs (name)); + } public void Dispose () { @@ -248,4 +265,14 @@ namespace MonoDevelop.Core return sb.ToString (); } } + + public class PropertyBagChangedEventArgs : EventArgs + { + public string PropertyName { get; private set; } + + public PropertyBagChangedEventArgs (string name) + { + PropertyName = name; + } + } } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Components.Commands/KeyBindingManager.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Components.Commands/KeyBindingManager.cs index 78c078b119..ced8041eb8 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Components.Commands/KeyBindingManager.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Components.Commands/KeyBindingManager.cs @@ -110,7 +110,7 @@ namespace MonoDevelop.Components.Commands return true; else if (key.Equals (Gdk.Key.Meta_L) || key.Equals (Gdk.Key.Meta_R)) return true; - else if (key.Equals (Gdk.Key.Super_L) || key.Equals (Gdk.Key.Super_L)) + else if (key.Equals (Gdk.Key.Super_L) || key.Equals (Gdk.Key.Super_R)) return true; return false; @@ -146,7 +146,7 @@ namespace MonoDevelop.Components.Commands label += "Shift+"; else if (key.Equals (Gdk.Key.Meta_L) || key.Equals (Gdk.Key.Meta_R)) label += "Meta+"; - else if (key.Equals (Gdk.Key.Super_L) || key.Equals (Gdk.Key.Super_L)) + else if (key.Equals (Gdk.Key.Super_L) || key.Equals (Gdk.Key.Super_R)) label += "Super+"; return label; diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Components.MainToolbar/MainToolbar.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Components.MainToolbar/MainToolbar.cs index 63fef7c610..5116cbade3 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Components.MainToolbar/MainToolbar.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Components.MainToolbar/MainToolbar.cs @@ -266,7 +266,7 @@ namespace MonoDevelop.Components.MainToolbar if (pattern.Pattern == null && pattern.LineNumber > 0) { popup.Destroy (); var doc = IdeApp.Workbench.ActiveDocument; - if (doc != null && doc != null) { + if (doc != null && doc.Editor != null) { doc.Select (); doc.Editor.Caret.Location = new Mono.TextEditor.DocumentLocation (pattern.LineNumber, pattern.Column > 0 ? pattern.Column : 1); doc.Editor.CenterToCaret (); diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Components/GtkUtil.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Components/GtkUtil.cs index 3e2e8f4248..706a62abbf 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Components/GtkUtil.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Components/GtkUtil.cs @@ -29,6 +29,7 @@ using System; using System.Collections.Generic; using Gtk; using System.Runtime.InteropServices; +using Mono.Addins; namespace MonoDevelop.Components { @@ -73,7 +74,54 @@ namespace MonoDevelop.Components { return (Gtk.Widget) Xwt.Toolkit.CurrentEngine.GetNativeWidget (widget); } - + + public static void DrawImage (this Cairo.Context s, Gtk.Widget widget, Xwt.Drawing.Image image, double x, double y) + { + Xwt.Toolkit.CurrentEngine.RenderImage (widget, s, image, x, y); + } + + public static Xwt.Drawing.Image ToXwtImage (this Gdk.Pixbuf pix) + { + return Xwt.Toolkit.CurrentEngine.WrapImage (pix); + } + + public static Gdk.Pixbuf ToPixbuf (this Xwt.Drawing.Image image) + { + return (Gdk.Pixbuf)Xwt.Toolkit.CurrentEngine.GetNativeImage (image); + } + + public static Gdk.Pixbuf ToPixbuf (this Xwt.Drawing.Image image, Gtk.IconSize size) + { + return (Gdk.Pixbuf)Xwt.Toolkit.CurrentEngine.GetNativeImage (image.WithSize (size)); + } + + public static Xwt.Drawing.Image WithSize (this Xwt.Drawing.Image image, Gtk.IconSize size) + { + int w, h; + if (!Gtk.Icon.SizeLookup (size, out w, out h)) + return image; + return image.WithSize (w, h); + } + + public static Xwt.Drawing.Image GetImageResource (this RuntimeAddin addin, string resource) + { + using (var s = addin.GetResource (resource)) { + var img = Xwt.Drawing.Image.FromStream (s); + int i = resource.LastIndexOf ('.'); + if (i != -1) { + var resource2x = resource.Substring (0, i) + "@2x" + resource.Substring (i); + var s2x = addin.GetResource (resource2x); + if (s2x != null) { + using (s2x) { + var img2x = Xwt.Drawing.Image.FromStream (s2x); + return Xwt.Drawing.Image.CreateMultiSizeIcon (new Xwt.Drawing.Image[] {img, img2x}); + } + } + } + return img; + } + } + public static void EnableAutoTooltips (this Gtk.TreeView tree) { TreeViewTooltipsData data = new TreeViewTooltipsData (); diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Extensions/OptionsDialogSection.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Extensions/OptionsDialogSection.cs index c1637c862b..b6fe71b785 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Extensions/OptionsDialogSection.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Extensions/OptionsDialogSection.cs @@ -28,6 +28,7 @@ using System; using Mono.Addins; using MonoDevelop.Core; +using MonoDevelop.Components; namespace MonoDevelop.Ide.Extensions { @@ -36,9 +37,15 @@ namespace MonoDevelop.Ide.Extensions [ExtensionNode ("Section")] public class OptionsDialogSection: OptionsPanelNode, ICloneable { - [NodeAttribute ()] + [NodeAttribute] string icon; + [NodeAttribute] + string headerImageResource; + + [NodeAttribute] + string headerFillerImageResource; + public OptionsDialogSection () { } @@ -55,6 +62,19 @@ namespace MonoDevelop.Ide.Extensions icon = value; } } + + public Xwt.Drawing.Image HeaderImage { get; set; } + + public Xwt.Drawing.Image HeaderFillerImageResource { get; set; } + + protected override void Read (NodeElement elem) + { + base.Read (elem); + if (headerImageResource != null) + HeaderImage = Addin.GetImageResource (headerImageResource); + if (headerFillerImageResource != null) + HeaderFillerImageResource = Addin.GetImageResource (headerFillerImageResource); + } public object Clone () { diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Dialogs/OptionsDialog.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Dialogs/OptionsDialog.cs index eb3d4cf629..be76e7f779 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Dialogs/OptionsDialog.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Dialogs/OptionsDialog.cs @@ -46,6 +46,8 @@ namespace MonoDevelop.Ide.Gui.Dialogs Gtk.HBox pageFrame; Gtk.Button buttonCancel; Gtk.Button buttonOk; + OptionsDialogHeader imageHeader; + Gtk.Alignment textHeader; protected TreeStore store; Dictionary<OptionsDialogSection, SectionPage> pages = new Dictionary<OptionsDialogSection, SectionPage> (); @@ -119,8 +121,14 @@ namespace MonoDevelop.Ide.Gui.Dialogs labelTitle = new Label (); labelTitle.Xalign = 0; - headerBox.PackStart (labelTitle, true, true, 0); - headerBox.BorderWidth = 12; + textHeader = new Alignment (0, 0, 1, 1); + textHeader.Add (labelTitle); + textHeader.BorderWidth = 12; + headerBox.PackStart (textHeader, true, true, 0); + + imageHeader = new OptionsDialogHeader (); + imageHeader.Hide (); + headerBox.PackStart (imageHeader.ToGtkWidget ()); var fboxHeader = new HeaderBox (); fboxHeader.SetMargins (0, 1, 0, 0); @@ -486,8 +494,16 @@ namespace MonoDevelop.Ide.Gui.Dialogs if (page.Widget == null) CreatePageWidget (page); - - labelTitle.Markup = "<span weight=\"bold\" size=\"large\">" + GLib.Markup.EscapeText (section.Label) + "</span>"; + + if (section.HeaderImage == null) { + labelTitle.Markup = "<span weight=\"bold\" size=\"large\">" + GLib.Markup.EscapeText (section.Label) + "</span>"; + textHeader.Show (); + imageHeader.Hide (); + } else { + imageHeader.SetImage (section.HeaderImage, section.HeaderFillerImageResource); + imageHeader.Show (); + textHeader.Hide (); + } //HACK: mimetype panels can't provide stock ID for mimetype images. Give this some awareness of mimetypes. var mimeSection = section as MonoDevelop.Ide.Projects.OptionPanels.MimetypeOptionsDialogSection; @@ -716,4 +732,37 @@ namespace MonoDevelop.Ide.Gui.Dialogs public Gtk.TreeIter Iter; } } + + class OptionsDialogHeader: Xwt.Canvas + { + Xwt.Drawing.Image image, filler; + + public void SetImage (Xwt.Drawing.Image image, Xwt.Drawing.Image filler) + { + this.image = image; + this.filler = filler; + QueueDraw (); + } + + protected override void OnDraw (Xwt.Drawing.Context ctx, Xwt.Rectangle dirtyRect) + { + base.OnDraw (ctx, dirtyRect); + if (image != null) { + ctx.DrawImage (image, 0, 0); + if (filler != null) { + int fillCount = (int)Math.Ceiling ((Bounds.Width - image.Width) / filler.Width); + double x = image.Width; + while ((fillCount--) > 0) { + ctx.DrawImage (filler, x, 0); + x += filler.Width; + } + } + } + } + + protected override Xwt.Size OnGetPreferredSize (Xwt.SizeConstraint widthConstraint, Xwt.SizeConstraint heightConstraint) + { + return new Xwt.Size (0, image != null ? image.Height : 0); + } + } } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ProjectPad/FolderNodeBuilder.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ProjectPad/FolderNodeBuilder.cs index e99bcec32d..f958a36b42 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ProjectPad/FolderNodeBuilder.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Gui.Pads.ProjectPad/FolderNodeBuilder.cs @@ -66,9 +66,10 @@ namespace MonoDevelop.Ide.Gui.Pads.ProjectPad Project project = builder.GetParentDataItem (typeof(Project), true) as Project; if (project == null) return; - + ProjectFileCollection files; - ArrayList folders; + List<string> folders; + GetFolderContent (project, path, out files, out folders); foreach (ProjectFile file in files) @@ -78,11 +79,12 @@ namespace MonoDevelop.Ide.Gui.Pads.ProjectPad builder.AddChild (new ProjectFolder (folder, project, dataObject)); } - void GetFolderContent (Project project, string folder, out ProjectFileCollection files, out ArrayList folders) + void GetFolderContent (Project project, string folder, out ProjectFileCollection files, out List<string> folders) { - files = new ProjectFileCollection (); - folders = new ArrayList (); string folderPrefix = folder + Path.DirectorySeparatorChar; + + files = new ProjectFileCollection (); + folders = new List<string> (); foreach (ProjectFile file in project.Files) { @@ -104,7 +106,7 @@ namespace MonoDevelop.Ide.Gui.Pads.ProjectPad dir = file.Name; // add the directory if it isn't already present - if (dir.StartsWith (folderPrefix)) { + if (dir.StartsWith (folderPrefix, StringComparison.Ordinal)) { int i = dir.IndexOf (Path.DirectorySeparatorChar, folderPrefix.Length); if (i != -1) dir = dir.Substring (0,i); if (!folders.Contains (dir)) diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/PortableRuntimeOptionsPanel.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/PortableRuntimeOptionsPanel.cs index f015c19935..4578e46a36 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/PortableRuntimeOptionsPanel.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.Projects.OptionPanels/PortableRuntimeOptionsPanel.cs @@ -25,6 +25,7 @@ using System; using System.IO; +using System.Text; using System.Linq; using System.Collections; using System.Collections.Generic; @@ -63,12 +64,21 @@ namespace MonoDevelop.Ide.Projects.OptionPanels static TargetFramework NetPortableProfile3; static TargetFramework NetPortableProfile4; - Dictionary<CheckButton, List<TargetFramework>> checkboxes = new Dictionary<CheckButton, List<TargetFramework>> (); - Dictionary<CheckButton, ComboBox> comboboxes = new Dictionary<CheckButton, ComboBox> (); + readonly TargetFramework missingFramework; + readonly List<TargetFramework> targetFrameworks; + readonly SortedDictionary<string, List<SupportedFramework>> supportedFrameworks; + readonly List<OptionCombo> options; + PortableDotNetProject project; TargetFramework target; HBox warningHBox; Label warning; + Image warningImage; + Image infoImage; + ComboBox selectorCombo; + bool disableEvents; + + const bool UseShortDescriptionInSelector = false; static void InitProfiles () { @@ -110,6 +120,40 @@ namespace MonoDevelop.Ide.Projects.OptionPanels NetPortableProfile4.SupportedFrameworks.Add (Silverlight); NetPortableProfile4.SupportedFrameworks.Add (WindowsPhone); } + + class OptionComboItem { + public readonly string Name; + public readonly SupportedFramework Framework; + public readonly List<TargetFramework> Targets; + + public OptionComboItem (string name, SupportedFramework sfx) + { + this.Name = name; + this.Framework = sfx; + this.Targets = new List<TargetFramework> (); + } + } + + class OptionCombo { + public readonly string Name; + public IList<OptionComboItem> Items; + public ComboBox Combo; + public CheckButton Check; + + public OptionComboItem Current { + get { + if (Combo != null) + return Items [Combo.Active]; + else + return Items [0]; + } + } + + public OptionCombo (string name) + { + Name = name; + } + } public PortableRuntimeOptionsPanelWidget (PortableDotNetProject project, IEnumerable<ItemConfiguration> configurations) { @@ -118,14 +162,21 @@ namespace MonoDevelop.Ide.Projects.OptionPanels this.Build (); // Aggregate all SupportedFrameworks from .NETPortable TargetFrameworks - SortedDictionary<string, List<SupportedFramework>> frameworks = new SortedDictionary<string, List<SupportedFramework>> (); - foreach (var fx in GetPortableTargetFrameworks ()) { + targetFrameworks = GetPortableTargetFrameworks ().ToList (); + supportedFrameworks = new SortedDictionary<string, List<SupportedFramework>> (); + + if (!targetFrameworks.Contains (project.TargetFramework)) { + missingFramework = project.TargetFramework; + targetFrameworks.Insert (0, project.TargetFramework); + } + + foreach (var fx in targetFrameworks) { foreach (var sfx in fx.SupportedFrameworks) { List<SupportedFramework> list; - if (!frameworks.TryGetValue (sfx.DisplayName, out list)) { + if (!supportedFrameworks.TryGetValue (sfx.DisplayName, out list)) { list = new List<SupportedFramework> (); - frameworks.Add (sfx.DisplayName, list); + supportedFrameworks.Add (sfx.DisplayName, list); } list.Add (sfx); @@ -133,47 +184,89 @@ namespace MonoDevelop.Ide.Projects.OptionPanels } // Now create a list of config options from our supported frameworks - var options = new List<SortedDictionary<string, List<TargetFramework>>> (); - foreach (var fx in frameworks) { - var dict = new SortedDictionary<string, List<TargetFramework>> (); - List<SupportedFramework> versions = fx.Value; - List<TargetFramework> targets; - string label; - - foreach (var sfx in versions) { - if (!string.IsNullOrEmpty (sfx.MinimumVersionDisplayName)) - label = sfx.DisplayName + " " + sfx.MinimumVersionDisplayName; - else - label = sfx.DisplayName; - - if (!dict.TryGetValue (label, out targets)) { - targets = new List<TargetFramework> (); - dict.Add (label, targets); + options = new List<OptionCombo> (); + foreach (var fx in supportedFrameworks) { + var combo = new OptionCombo (fx.Key); + + var dict = new SortedDictionary<string, OptionComboItem> (); + foreach (var sfx in fx.Value) { + var label = GetDisplayName (sfx); + + OptionComboItem item; + if (!dict.TryGetValue (label, out item)) { + item = new OptionComboItem (label, sfx); + dict.Add (label, item); } - targets.Add (sfx.TargetFramework); + item.Targets.Add (sfx.TargetFramework); } - options.Add (dict); - } + combo.Items = dict.Values.ToList (); - // Add multi-option combo boxes first - foreach (var opt in options) { - if (opt.Count > 1) - AddMultiOptionCombo (opt); + options.Add (combo); } - // Now add the single-option check boxes - foreach (var opt in options) { - if (opt.Count == 1) { - var kvp = opt.FirstOrDefault (); + CreateUI (); - AddSingleOptionCheckbox (kvp.Key, kvp.Value); - } + CurrentProfileChanged (project.TargetFramework); + } + + static string GetDisplayName (SupportedFramework sfx) + { + if (!string.IsNullOrEmpty (sfx.MinimumVersionDisplayName)) + return sfx.DisplayName + " " + sfx.MinimumVersionDisplayName; + else if (!string.IsNullOrEmpty (sfx.MonoSpecificVersionDisplayName)) + return sfx.DisplayName + " " + sfx.MonoSpecificVersionDisplayName; + else + return sfx.DisplayName; + } + + static string GetShortName (SupportedFramework sfx) + { + switch (sfx.DisplayName) { + case ".NET Framework": + return "NET" + sfx.MinimumVersionDisplayName.Replace (".", ""); + case "Silverlight": + return "SL" + sfx.MinimumVersionDisplayName; + case "Xamarin.Android": + return "Android"; + case ".NET for Windows Store apps": + return "WinStore"; + case "Windows Phone": + return "WP" + sfx.MinimumVersionDisplayName.Replace (".", ""); + case "Xbox 360": + return "XBox"; + case "Xamarin.iOS": + if (string.IsNullOrEmpty (sfx.MonoSpecificVersionDisplayName)) + return "iOS"; + else + return "iOS/" + sfx.MonoSpecificVersion; + default: + return GetDisplayName (sfx); } + } - AddWarningLabel (); - UpdateWarning (); + string FormatTargetFramework (TargetFramework fx) + { + string description; + if (fx == missingFramework) + description = " - not installed"; + else if (UseShortDescriptionInSelector) { + var sb = new StringBuilder (); + sb.Append (" ("); + foreach (var sfx in fx.SupportedFrameworks) { + var label = GetShortName (sfx); + if (sb.Length > 2) + sb.Append (", "); + sb.Append (label); + } + sb.Append (")"); + description = sb.ToString (); + } else + description = string.Empty; + + return string.Format ( + "{0} - {1}{2}", fx.Id.Version, fx.Id.Profile, description); } IEnumerable<TargetFramework> GetPortableTargetFrameworks () @@ -200,216 +293,421 @@ namespace MonoDevelop.Ide.Projects.OptionPanels yield return NetPortableProfile4; } - void AddMultiOptionCombo (SortedDictionary<string, List<TargetFramework>> options) + void CreateUI () { - var alignment = new Alignment (0.0f, 0.5f, 1.0f, 1.0f) { LeftPadding = 18 }; - var model = new ListStore (new Type[] { typeof (string), typeof (object) }); - var renderer = new CellRendererText (); - var combo = new ComboBox (model); - var check = new CheckButton (); - List<TargetFramework> targets; - var hbox = new HBox (); - int current = 0; - int active = -1; - string label; + AddLabel ("Current Profile:", 0); - foreach (var kvp in options) { - label = kvp.Key; + AddTopSelectorCombo (); - if (current + 1 < options.Count) - label += " or later"; + AddLabel ("Target Frameworks:", 18); - targets = kvp.Value; - if (active == -1) { - foreach (var target in targets) { - if (target.Id.Equals (project.TargetFramework.Id)) { - active = current; - break; - } - } - } + // Add multi-option combo boxes first + foreach (var opt in options) { + if (opt.Items.Count > 1) + AddMultiOptionCombo (opt); + } - model.AppendValues (label, targets); - current++; + // Now add the single-option check boxes + foreach (var opt in options) { + if (opt.Items.Count == 1) + AddSingleOptionCheckbox (opt); } - combo.PackStart (renderer, true); - combo.AddAttribute (renderer, "text", 0); + AddWarningLabel (); + } - check.Show (); - combo.Show (); + void AddLabel (string text, uint top) + { + var label = new Label (text); + label.SetAlignment (0.0f, 0.5f); + label.Show (); - if (active != -1) { - combo.Active = active; - check.Active = true; - } else { - check.Active = false; - combo.Active = 0; + var alignment = new Alignment (0.0f, 0.5f, 1.0f, 1.0f) { + TopPadding = top, BottomPadding = 4 + }; + alignment.Add (label); + alignment.Show (); + + vbox1.PackStart (alignment, false, true, 0); + } + + void AddTopSelectorCombo () + { + var model = new ListStore (new Type[] { typeof (string), typeof (object) }); + var renderer = new CellRendererText (); + var combo = selectorCombo = new ComboBox (model); + + for (int i = 0; i < targetFrameworks.Count; i++) { + var fx = targetFrameworks [i]; + + model.AppendValues (FormatTargetFramework (fx), fx); + if (fx.Id.Equals (project.TargetFramework.Id)) + combo.Active = i; } + combo.PackStart (renderer, true); + combo.SetCellDataFunc (renderer, (l, c, m, i) => { + ((CellRendererText)c).Text = (string)model.GetValue (i, 0); + }); + + combo.Show (); + combo.Changed += (sender, e) => { - if (check.Active) - TargetFrameworkChanged (check, combo); + if (combo.Active >= 0) + CurrentProfileChanged (targetFrameworks [combo.Active]); }; - check.Toggled += (sender, e) => { - TargetFrameworkChanged (check, combo); + + var alignment = new Alignment (0.0f, 0.5f, 1.0f, 1.0f) { + LeftPadding = 18, RightPadding = 18 }; + alignment.Add (combo); + + alignment.Show (); + + vbox1.PackStart (alignment, false, true, 0); + } + + void AddMultiOptionCombo (OptionCombo option) + { + if (option.Items.Count < 2) + throw new InvalidOperationException (); + + var model = new ListStore (new Type[] { typeof (string), typeof (object) }); + var renderer = new CellRendererText (); + + foreach (var item in option.Items) { + var label = item.Name; + var sfx = item.Framework; + + bool hasOtherVersions = false; + foreach (var other in option.Items) { + if (sfx == other.Framework) + continue; + if (!string.IsNullOrEmpty (other.Framework.MonoSpecificVersionDisplayName)) + continue; + hasOtherVersions = true; + break; + } - comboboxes.Add (check, combo); + if (hasOtherVersions && string.IsNullOrEmpty (sfx.MonoSpecificVersionDisplayName)) + label += " or later"; + + model.AppendValues (label, item.Targets); + } + + option.Combo = new ComboBox (model); + option.Check = new CheckButton (); + + option.Combo.PackStart (renderer, true); + option.Combo.AddAttribute (renderer, "text", 0); + + option.Combo.Active = 0; - hbox.PackStart (check, false, false, 0); - hbox.PackStart (combo, false, true, 0); + option.Check.Show (); + option.Combo.Show (); + + option.Combo.Changed += (sender, e) => { + if (option.Check.Active) + TargetFrameworkChanged (option); + }; + option.Check.Toggled += (sender, e) => { + TargetFrameworkChanged (option); + }; + + var hbox = new HBox (); + hbox.PackStart (option.Check, false, false, 0); + hbox.PackStart (option.Combo, true, true, 0); hbox.Show (); + var alignment = new Alignment (0.0f, 0.5f, 1.0f, 1.0f) { + LeftPadding = 18, RightPadding = 18 + }; alignment.Add (hbox); alignment.Show (); - vbox1.PackStart (alignment, false, false, 0); + vbox1.PackStart (alignment, false, true, 0); } - void AddSingleOptionCheckbox (string label, List<TargetFramework> targetFrameworks) + void AddSingleOptionCheckbox (OptionCombo option) { - var alignment = new Alignment (0.0f, 0.5f, 1.0f, 1.0f) { LeftPadding = 18 }; - var check = new CheckButton (label); + if (option.Items.Count != 1) + throw new InvalidOperationException (); - foreach (var fx in targetFrameworks) { - if (fx.Id.Equals (project.TargetFramework.Id)) { - check.Active = true; - break; - } - } + option.Check = new CheckButton (option.Items [0].Name); - check.Toggled += (sender, e) => { - TargetFrameworkChanged (check, targetFrameworks); + option.Check.Toggled += (sender, e) => { + TargetFrameworkChanged (option); }; - checkboxes.Add (check, targetFrameworks); + option.Check.Show (); - check.Show (); - alignment.Add (check); + var alignment = new Alignment (0.0f, 0.5f, 1.0f, 1.0f) { + LeftPadding = 18, RightPadding = 18 + }; + alignment.Add (option.Check); alignment.Show (); - vbox1.PackStart (alignment, false, false, 0); + vbox1.PackStart (alignment, false, true, 0); } void AddWarningLabel () { - var alignment = new Alignment (0.0f, 0.5f, 1.0f, 1.0f) { LeftPadding = 18 }; - var image = new Image (GetType ().Assembly, "warning-16.png"); + var alignment = new Alignment (0.0f, 0.5f, 1.0f, 1.0f) { + TopPadding = 8, LeftPadding = 18, RightPadding = 18 + }; - warning = new Label (""); + warning = new Label ("Test Error"); warning.SetAlignment (0.0f, 0.5f); warning.Show (); - image.Show (); + + infoImage = new Image (GetType ().Assembly, "warning-16.png"); + warningImage = new Image (GetType ().Assembly, "error-16.png"); warningHBox = new HBox (false, 6); - warningHBox.PackStart (image, false, false, 0); + warningHBox.PackStart (infoImage, false, false, 0); + warningHBox.PackStart (warningImage, false, false, 0); warningHBox.PackStart (warning, false, true, 0); alignment.Child = warningHBox; alignment.Show (); - vbox1.PackStart (alignment, false, false, 0); + vbox1.PackStart (alignment, false, true, 0); } - List<TargetFramework> GetTargetFrameworks (ComboBox combo) + void ClearWarnings () { - TreeIter iter; + warning.LabelProp = string.Empty; + warningHBox.Hide (); - if (!combo.GetActiveIter (out iter)) - return new List<TargetFramework> (); + infoImage.Hide (); + warningImage.Hide (); + } - return (List<TargetFramework>) combo.Model.GetValue (iter, 1); + void SetWarning (string message) + { + warning.LabelProp = message; + infoImage.Hide (); + warningImage.Show (); + warningHBox.Show (); } - TargetFramework GetTargetFramework (CheckButton checkbox, List<TargetFramework> initial) + void SetWarning (string message, params object[] args) { - var list = new List<TargetFramework> (initial); - int nchecked = 0; + SetWarning (string.Format (message, args)); + } - foreach (var kvp in comboboxes) { - var combo = kvp.Value; - var check = kvp.Key; + void AddWarning (string message, params object[] args) + { + AddWarning (string.Format (message, args)); + } - if (check.Active) - nchecked++; + void AddWarning (string message) + { + if (!string.IsNullOrEmpty (warning.LabelProp)) + warning.LabelProp += Environment.NewLine; + warning.LabelProp += message; + infoImage.Hide (); + warningImage.Show (); + warningHBox.Show (); + } - if (!check.Active || check == checkbox) - continue; + void AddInfo (string message, params object[] args) + { + AddInfo (string.Format (message, args)); + } - var filtered = new List<TargetFramework> (); - foreach (var target in GetTargetFrameworks (combo)) { - if (list.Contains (target)) - filtered.Add (target); - } - list = filtered; + void AddInfo (string message) + { + if (string.IsNullOrEmpty (warning.LabelProp)) { + warningImage.Hide (); + infoImage.Show (); + } else { + warning.LabelProp += Environment.NewLine; } + warning.LabelProp += message; + warningHBox.Show (); + } - foreach (var kvp in checkboxes) { - var targets = kvp.Value; - var check = kvp.Key; + void TargetFrameworkChanged (OptionCombo option) + { + if (disableEvents) + return; - if (check.Active) - nchecked++; - - if (!check.Active || check == checkbox) - continue; - - var filtered = new List<TargetFramework> (); - foreach (var target in targets) { - if (list.Contains (target)) - filtered.Add (target); - } - list = filtered; + try { + disableEvents = true; + TargetFrameworkChanged_internal (option); + } finally { + disableEvents = false; } + } - // Choose the TargetFramework with the smallest subset of supported frameworks - TargetFramework smallest = this.target; - int min = Int32.MaxValue; + void TargetFrameworkChanged_internal (OptionCombo option) + { + ClearWarnings (); + selectorCombo.Active = -1; - foreach (var target in list) { - if (target.SupportedFrameworks.Count < min) { - min = target.SupportedFrameworks.Count; - smallest = target; - } + // The currently selected combo boxes. + var selectedOptions = options.Where (o => o.Check.Active).ToList (); + + if (selectedOptions.Count < 2) { + SetWarning ("Need to select at least two frameworks."); + return; } - return smallest; + // SupportedFramework from each of the currently selected combo boxes. + var selectedFrameworks = selectedOptions.Select (s => s.Current.Framework).ToList (); + SelectFrameworks (selectedFrameworks); } - void UpdateWarning () + void SelectFrameworks (List<SupportedFramework> selectedFrameworks) { - if (target.SupportedFrameworks.Count > 0) { - warningHBox.Hide (); + // Which TargetFramework's match these? + var applicable = targetFrameworks.Where ( + f => IsApplicable (f, true, selectedFrameworks)).ToList (); + + if (applicable.Count == 0) { + AddWarning ("No applicable frameworks for this selection!"); return; } - var moniker = target.Id.Profile == null ? TargetFrameworkMoniker.PORTABLE_4_0 : target.Id; - warning.LabelProp = GettextCatalog.GetString ("The {0} framework is not installed.", moniker); + // + // 'applicable' contains all TargetFrameworks that match _at least_ + // the list of 'selectedFrameworks'. + // + // 'exactMatches' is where they do not contain any additional + // (non-selected) 'SupportedFramework's. + // + + var exactMatches = applicable.Where ( + a => IsApplicable (a, false, selectedFrameworks)).ToList (); + if (exactMatches.Count == 1) { + // Found an exact match. + SelectFramework (exactMatches [0]); + return; + } else if (exactMatches.Count > 1) { + // This should never happen. + AddWarning ("Multiple frameworks match the current selection:"); + exactMatches.ForEach (e => AddWarning (" " + e.Id)); + AddWarning ("You must manually pick a profile in the drop-down selector."); + // This is very bad UX, we should really disable "Ok" / add an "Apply" + // button, but it's better than nothing. + target = exactMatches [0]; + return; + } - warningHBox.Show (); + // Union of all the SupportedFrameworks from our applicable TargetFrameworks. + var all = applicable.SelectMany ( + a => a.SupportedFrameworks).Distinct (SupportedFramework.EqualityComparer); + + // Minus the ones that we already selected. + var extra = all.Where (a => !selectedFrameworks.Contains (a)).ToList (); + + // Are there any SupportedFrameworks that all our applicable TargetFrameworks + // have in common? + var common = extra.Where ( + e => applicable.All (a => a.SupportedFrameworks.Contains (e))).ToList (); + + if (common.Count == 0) { + // Ok, the user must pick something. + AddWarning ("Found multiple applicable frameworks, you need to " + + "select additional check boxes."); + // Same here: randomly pick a profile to make "Ok" happy. + target = applicable [0]; + return; + } + + AddInfo ("The following frameworks have been implicitly selected:"); + AddInfo (" " + string.Join (", ", common.Select (c => GetDisplayName (c)))); + + // Implicitly select them. + var implicitlySelected = new List<SupportedFramework> (); + implicitlySelected.AddRange (selectedFrameworks); + implicitlySelected.AddRange (common); + + // And let's try again ... + SelectFrameworks (implicitlySelected); } - void TargetFrameworkChanged (CheckButton check, List<TargetFramework> targetFrameworks) + void SelectOption (SupportedFramework sfx) { - if (!check.Active) - targetFrameworks = new List<TargetFramework> (GetPortableTargetFrameworks ()); + foreach (var option in options) { + for (int i = 0; i < option.Items.Count; i++) { + var item = option.Items [i]; + if (!item.Framework.Equals (sfx)) + continue; + + option.Check.Active = true; + if (option.Combo != null) + option.Combo.Active = i; + return; + } + } - target = GetTargetFramework (check, targetFrameworks); - UpdateWarning (); + throw new InvalidOperationException (); } - void TargetFrameworkChanged (CheckButton check, ComboBox combo) + void SelectFramework (TargetFramework framework) { - List<TargetFramework> targetFrameworks; + var frameworks = targetFrameworks.Select ((t, i) => new { Framework = t, Index = i }); + var index = frameworks.First (t => t.Framework == framework).Index; + selectorCombo.Active = index; + target = framework; + } - if (!check.Active) - targetFrameworks = new List<TargetFramework> (GetPortableTargetFrameworks ()); - else - targetFrameworks = GetTargetFrameworks (combo); + bool IsApplicable (TargetFramework fx, bool allowExtra, IEnumerable<SupportedFramework> selected) + { + return IsApplicable (fx, allowExtra, selected.ToArray ()); + } - target = GetTargetFramework (check, targetFrameworks); - UpdateWarning (); + bool IsApplicable (TargetFramework fx, bool allowExtra, params SupportedFramework[] required) + { + if (fx == missingFramework) + return false; + + var present = new List<SupportedFramework> (fx.SupportedFrameworks); + var matches = required.All (r => present.Remove (r)); + return matches && (allowExtra || present.Count == 0); + } + + void CurrentProfileChanged (TargetFramework framework) + { + if (disableEvents) + return; + + try { + disableEvents = true; + CurrentProfileChanged_internal (framework); + target = framework; + } finally { + disableEvents = false; + } + } + + void CurrentProfileChanged_internal (TargetFramework framework) + { + ClearWarnings (); + + foreach (var option in options) { + var sfx = framework.SupportedFrameworks.FirstOrDefault ( + s => s.DisplayName.Equals (option.Name)); + if (sfx == null) { + option.Check.Active = false; + continue; + } + + option.Check.Active = true; + + if (option.Combo == null) + continue; + + var label = GetDisplayName (sfx); + for (int i = 0; i < option.Items.Count; i++) { + if (!option.Items [i].Name.Equals (label)) + continue; + option.Combo.Active = i; + break; + } + } } public void Store () diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/TypeSystemService.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/TypeSystemService.cs index e290e1f437..350d0c4457 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/TypeSystemService.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.TypeSystem/TypeSystemService.cs @@ -56,21 +56,42 @@ namespace MonoDevelop.Ide.TypeSystem { public static class TypeSystemServiceExt { + [Obsolete("Don't use this method the caller should always have the project and get the type system from that instead the other way around.")] public static Project GetProject (this IProjectContent content) { return TypeSystemService.GetProject (content.Location); } - + + [Obsolete("Don't use this method the caller should always have the project and get the type system from that instead the other way around.")] public static Project GetSourceProject (this ITypeDefinition type) { - return TypeSystemService.GetProject (type.ParentAssembly.UnresolvedAssembly.Location); + var location = type.Compilation.MainAssembly.UnresolvedAssembly.Location; + if (string.IsNullOrEmpty (location)) + return null; + return TypeSystemService.GetProject (location); } + [Obsolete("Don't use this method the caller should always have the project and get the type system from that instead the other way around.")] public static Project GetSourceProject (this IType type) { return type.GetDefinition ().GetSourceProject (); } - + + internal static Project GetProjectWhereTypeIsDefined (this ITypeDefinition type) + { + var location = type.ParentAssembly.UnresolvedAssembly.Location; + if (string.IsNullOrEmpty (location)) + return null; + return TypeSystemService.GetProject (location); + } + + internal static Project GetProjectWhereTypeIsDefined (this IType type) + { + return type.GetDefinition ().GetSourceProject (); + } + + + [Obsolete("Don't use this method the caller should always have the project and get the type system from that instead the other way around.")] public static IProjectContent GetProjectContent (this IType type) { return TypeSystemService.GetProjectContext (type.GetSourceProject ()); @@ -1091,7 +1112,7 @@ namespace MonoDevelop.Ide.TypeSystem class LazyProjectLoader : IProjectContent { readonly ProjectContentWrapper wrapper; - Task<IProjectContent> contextTask; + readonly Task<IProjectContent> contextTask; public Task<IProjectContent> ContextTask { get { @@ -1109,15 +1130,21 @@ namespace MonoDevelop.Ide.TypeSystem { this.wrapper = wrapper; contextTask = Task.Factory.StartNew (delegate { - var context = LoadProjectCache (this.wrapper.Project); + var p = this.wrapper.Project; + var context = LoadProjectCache (p); + + var assemblyName = p.ParentSolution != null ? p.GetOutputFileName (p.ParentSolution.DefaultConfigurationSelector).FileNameWithoutExtension : p.Name; + if (string.IsNullOrEmpty (assemblyName)) + assemblyName = p.Name; + if (context != null) { - return context.SetAssemblyName (this.wrapper.Project.Name) ?? context; + return context.SetAssemblyName (assemblyName) ?? context; } - context = new MonoDevelopProjectContent (this.wrapper.Project); + context = new MonoDevelopProjectContent (p); wrapper.InLoad = true; - context = context.SetLocation (this.wrapper.Project.FileName); - context = context.SetAssemblyName (this.wrapper.Project.Name); + context = context.SetLocation (p.FileName); + context = context.SetAssemblyName (assemblyName); QueueParseJob (this.wrapper); return context; }); diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.WelcomePage/WelcomePageRecentProjectsList.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.WelcomePage/WelcomePageRecentProjectsList.cs index e16036de62..2f7c07f902 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.WelcomePage/WelcomePageRecentProjectsList.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide.WelcomePage/WelcomePageRecentProjectsList.cs @@ -37,11 +37,11 @@ namespace MonoDevelop.Ide.WelcomePage public class WelcomePageRecentProjectsList : WelcomePageSection
{
bool destroyed;
- EventHandler recentChangesHandler;
- VBox box;
+ readonly EventHandler recentChangesHandler;
+ readonly VBox box;
int itemCount = 10;
- Gdk.Pixbuf openProjectIcon;
- Gdk.Pixbuf newProjectIcon;
+ readonly Gdk.Pixbuf openProjectIcon;
+ readonly Gdk.Pixbuf newProjectIcon;
public WelcomePageRecentProjectsList (string title = null, int count = 10): base (title)
{
@@ -98,6 +98,9 @@ namespace MonoDevelop.Ide.WelcomePage //TODO: pinned files
foreach (var recent in DesktopService.RecentFiles.GetProjects ().Take (itemCount)) {
var filename = recent.FileName;
+ if (!System.IO.File.Exists (filename))
+ continue;
+
var accessed = recent.TimeStamp;
var pixbuf = ImageService.GetPixbuf (GetIcon (filename), IconSize.Dnd);
var button = new WelcomePageListButton (recent.DisplayName, System.IO.Path.GetDirectoryName (filename), pixbuf, "project://" + filename);
@@ -141,8 +144,6 @@ namespace MonoDevelop.Ide.WelcomePage //string icon;
//getting the icon requires probing the file, so handle IO errors
try {
- if (!System.IO.File.Exists (fileName))
- return null;
/* delay project service creation.
icon = IdeApp.Services.ProjectService.FileFormats.GetFileFormats
(fileName, typeof(Solution)).Length > 0
diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Ide.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Ide.cs index adb2de294e..9455cd1a36 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Ide.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/Ide.cs @@ -387,6 +387,7 @@ namespace MonoDevelop.Ide { // finally run the workbench window ... Gtk.Application.Run (); + Mono.TextEditor.GtkWorkarounds.Terminate (); } diff --git a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/ProjectOperations.cs b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/ProjectOperations.cs index 859979e227..0fd59d521b 100644 --- a/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/ProjectOperations.cs +++ b/main/src/core/MonoDevelop.Ide/MonoDevelop.Ide/ProjectOperations.cs @@ -287,7 +287,7 @@ namespace MonoDevelop.Ide } else { fileName = entity.Region.FileName; } - var project = (entity is ITypeDefinition ? ((ITypeDefinition )entity) : entity.DeclaringTypeDefinition).GetSourceProject (); + var project = (entity is ITypeDefinition ? ((ITypeDefinition )entity) : entity.DeclaringTypeDefinition).GetProjectWhereTypeIsDefined (); var doc = IdeApp.Workbench.OpenDocument (fileName, project, entity.Region.BeginLine, @@ -1610,7 +1610,7 @@ namespace MonoDevelop.Ide var virtualPath = sourcePath.ToRelative (sourceProject.BaseDirectory); // Grab all the child nodes of the folder we just dragged/dropped filesToRemove = sourceProject.Files.GetFilesInVirtualPath (virtualPath).ToList (); - // Add the folder itself so we can remove it from the soruce project if its a Move operation + // Add the folder itself so we can remove it from the source project if its a Move operation var folder = sourceProject.Files.FirstOrDefault (f => f.ProjectVirtualPath == virtualPath); if (folder != null) filesToRemove.Add (folder); diff --git a/main/src/core/MonoDevelop.Ide/gtk-gui/MonoDevelop.Ide.Projects.OptionPanels.PortableRuntimeOptionsPanelWidget.cs b/main/src/core/MonoDevelop.Ide/gtk-gui/MonoDevelop.Ide.Projects.OptionPanels.PortableRuntimeOptionsPanelWidget.cs index b3fe924608..ad4ec5a2c3 100644 --- a/main/src/core/MonoDevelop.Ide/gtk-gui/MonoDevelop.Ide.Projects.OptionPanels.PortableRuntimeOptionsPanelWidget.cs +++ b/main/src/core/MonoDevelop.Ide/gtk-gui/MonoDevelop.Ide.Projects.OptionPanels.PortableRuntimeOptionsPanelWidget.cs @@ -5,7 +5,6 @@ namespace MonoDevelop.Ide.Projects.OptionPanels public partial class PortableRuntimeOptionsPanelWidget { private global::Gtk.VBox vbox1; - private global::Gtk.Label labelTargetFrameworks; protected virtual void Build () { @@ -17,16 +16,6 @@ namespace MonoDevelop.Ide.Projects.OptionPanels this.vbox1 = new global::Gtk.VBox (); this.vbox1.Name = "vbox1"; this.vbox1.Spacing = 6; - // Container child vbox1.Gtk.Box+BoxChild - this.labelTargetFrameworks = new global::Gtk.Label (); - this.labelTargetFrameworks.Name = "labelTargetFrameworks"; - this.labelTargetFrameworks.Xalign = 0F; - this.labelTargetFrameworks.LabelProp = global::Mono.Unix.Catalog.GetString ("Target Frameworks:"); - this.vbox1.Add (this.labelTargetFrameworks); - global::Gtk.Box.BoxChild w1 = ((global::Gtk.Box.BoxChild)(this.vbox1 [this.labelTargetFrameworks])); - w1.Position = 0; - w1.Expand = false; - w1.Fill = false; this.Add (this.vbox1); if ((this.Child != null)) { this.Child.ShowAll (); diff --git a/main/src/core/MonoDevelop.Ide/gtk-gui/gui.stetic b/main/src/core/MonoDevelop.Ide/gtk-gui/gui.stetic index 4b610a2fcd..6ee8c8300b 100644 --- a/main/src/core/MonoDevelop.Ide/gtk-gui/gui.stetic +++ b/main/src/core/MonoDevelop.Ide/gtk-gui/gui.stetic @@ -12048,19 +12048,6 @@ Visual Studio generates a default ID for embedded resources, instead of simply u <property name="MemberName" /> <property name="Spacing">6</property> <child> - <widget class="Gtk.Label" id="labelTargetFrameworks"> - <property name="MemberName" /> - <property name="Xalign">0</property> - <property name="LabelProp" translatable="yes">Target Frameworks:</property> - </widget> - <packing> - <property name="Position">0</property> - <property name="AutoSize">True</property> - <property name="Expand">False</property> - <property name="Fill">False</property> - </packing> - </child> - <child> <placeholder /> </child> </widget> diff --git a/main/src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/RtfWriterTests.cs b/main/src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/RtfWriterTests.cs index 1b191923af..3bf883fbda 100644 --- a/main/src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/RtfWriterTests.cs +++ b/main/src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/RtfWriterTests.cs @@ -94,6 +94,7 @@ namespace Mono.TextEditor.Tests }", generatedRtf); } + [Ignore("Fixme")] [Test] public void TestXml () { @@ -104,6 +105,7 @@ namespace Mono.TextEditor.Tests />"); data.ColorStyle = SyntaxModeService.GetColorStyle ("TangoLight"); data.Document.SyntaxMode = SyntaxModeService.GetSyntaxMode (data.Document, "application/xml"); + string generatedRtf = RtfWriter.GenerateRtf (data); Assert.AreEqual ( @"{\rtf1\ansi\deff0\adeflang1025 diff --git a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/Commands.cs b/main/src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/SearchAndReplaceTests.cs index b9459b2937..3a501991e0 100644 --- a/main/src/addins/VersionControl/MonoDevelop.VersionControl.Subversion/MonoDevelop.VersionControl.Subversion/Commands.cs +++ b/main/src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/SearchAndReplaceTests.cs @@ -1,9 +1,10 @@ -// Commands.cs +// +// SearchAndReplaceTests.cs // // Author: -// Lluis Sanchez Gual <lluis@novell.com> +// Mike Krüger <mkrueger@xamarin.com> // -// Copyright (c) 2008 Novell, Inc (http://www.novell.com) +// Copyright (c) 2013 Xamarin Inc. (http://xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal @@ -22,15 +23,27 @@ // 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 NUnit.Framework; +using Gtk; -namespace MonoDevelop.VersionControl.Subversion +namespace Mono.TextEditor.Tests { - public enum Commands + [TestFixture] + public class SearchAndReplaceTests : TextEditorTestBase { - Resolve + /// <summary> + /// Bug 14716 - Search and replace All doesn't + /// </summary> + [Test()] + public void TestBug14716 () + { + var data = new TextEditorData (); + data.Document.Text = "using System;\nusing System.Linq;\nusing System.Collections.Generic;\n"; + data.SearchEngine = new RegexSearchEngine (); + data.SearchEngine.SearchRequest.SearchPattern = "u.i.g"; + data.SearchReplaceAll ("bar"); + Assert.AreEqual ("bar System;\nbar System.Linq;\nbar System.Collections.Generic;\n", data.Document.Text ); + } } -} +}
\ No newline at end of file diff --git a/main/src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/VirtualSpacesTests.cs b/main/src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/VirtualSpacesTests.cs index 59e12e14e1..786622bf14 100644 --- a/main/src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/VirtualSpacesTests.cs +++ b/main/src/core/MonoDevelop.TextEditor.Tests/Mono.TextEditor.Tests/VirtualSpacesTests.cs @@ -41,6 +41,7 @@ namespace Mono.TextEditor.Tests public void TestBug615196 () { TextEditorData data = new Mono.TextEditor.TextEditorData (); + data.IndentationTracker = null; data.Options.IndentStyle = IndentStyle.Auto; data.Document.Text = "\n\nHello World\n"; data.Caret.Offset = 1; // 2nd.Line @@ -61,6 +62,7 @@ namespace Mono.TextEditor.Tests public void TestBug613770 () { TextEditorData data = new Mono.TextEditor.TextEditorData (); + data.IndentationTracker = null; data.Options.IndentStyle = IndentStyle.Auto; data.Document.Text = "\n\n\n"; data.Caret.Offset = 1; // 2nd.Line @@ -75,6 +77,7 @@ namespace Mono.TextEditor.Tests public void TestReturnKeyBehavior () { TextEditorData data = new Mono.TextEditor.TextEditorData (); + data.IndentationTracker = null; data.Options.IndentStyle = IndentStyle.Auto; data.Document.Text = "\n\n\n"; data.Caret.Offset = 1; // 2nd.Line diff --git a/main/src/core/MonoDevelop.TextEditor.Tests/MonoDevelop.TextEditor.Tests.csproj b/main/src/core/MonoDevelop.TextEditor.Tests/MonoDevelop.TextEditor.Tests.csproj index 9b2285bfa0..bdcf53a2f2 100644 --- a/main/src/core/MonoDevelop.TextEditor.Tests/MonoDevelop.TextEditor.Tests.csproj +++ b/main/src/core/MonoDevelop.TextEditor.Tests/MonoDevelop.TextEditor.Tests.csproj @@ -80,6 +80,7 @@ <Compile Include="Mono.TextEditor.Tests\ClipboardTests.cs" /> <Compile Include="Mono.TextEditor.Tests\CompressingTreeListTests.cs" /> <Compile Include="Mono.TextEditor.Tests\AvlTreeTests.cs" /> + <Compile Include="Mono.TextEditor.Tests\SearchAndReplaceTests.cs" /> </ItemGroup> <Import Project="$(MSBuildBinPath)\Microsoft.CSharp.targets" /> <ItemGroup> diff --git a/main/tests/UnitTests/MonoDevelop.CSharpBinding/OnTheFlyFormatterTests.cs b/main/tests/UnitTests/MonoDevelop.CSharpBinding/OnTheFlyFormatterTests.cs index 4795d3b317..6ce5b0b405 100644 --- a/main/tests/UnitTests/MonoDevelop.CSharpBinding/OnTheFlyFormatterTests.cs +++ b/main/tests/UnitTests/MonoDevelop.CSharpBinding/OnTheFlyFormatterTests.cs @@ -51,10 +51,11 @@ namespace MonoDevelop.CSharpBinding { TestWorkbenchWindow tww = new TestWorkbenchWindow (); content = new TestViewContent (); + content.Data.Options.IndentStyle = IndentStyle.Auto; tww.ViewContent = content; content.ContentName = "a.cs"; content.GetTextEditorData ().Document.MimeType = "text/x-csharp"; - + Document doc = new Document (tww); var text = input; @@ -167,7 +168,37 @@ namespace MonoDevelop.CSharpBinding Assert.AreEqual ("@\"\t\"", newText); } + /// <summary> + /// Bug 14686 - Relative path strings containing backslashes have incorrect behavior when removing the @ symbol. + /// </summary> + [Test] + public void TestBug14686 () + { + TestViewContent content; + var ext = Setup ("$\"\\\\\"", out content); + content.GetTextEditorData ().Insert (0, "@"); + ext.KeyPress ((Gdk.Key)'@', '@', Gdk.ModifierType.None); + var newText = content.Text; + Assert.AreEqual ("@\"\\\"", newText); + } + + [Test] + public void TestBug14686Case2 () + { + TestViewContent content; + var ext = Setup ("$\"\\\"", out content); + content.GetTextEditorData ().Insert (0, "@"); + ext.KeyPress ((Gdk.Key)'@', '@', Gdk.ModifierType.None); + var newText = content.Text; + Assert.AreEqual ("@\"\\\"", newText); + ext = Setup ("$\"\\\"a", out content); + content.GetTextEditorData ().Insert (0, "@"); + ext.KeyPress ((Gdk.Key)'@', '@', Gdk.ModifierType.None); + newText = content.Text; + Assert.AreEqual ("@\"\\\"a", newText); + + } [Test] public void TestCorrectReindentNextLine () { |