Exemplo n.º 1
0
		public sealed override object GetViewObject(DecompilerTextView textView) {
			var obj = uiObjRef == null ? null : (FrameworkElement)uiObjRef.Target;
			// The element is cached but could be opened in two different tab groups. Only return
			// the cached one if it's not in use.
			if (obj != null && obj.Parent == null)
				return obj;

			FrameworkElement newObj;
			if (IsVirtualizingCollectionVM)
				newObj = new ContentPresenter() { Content = ViewObject, Focusable = true };
			else {
				newObj = new ScrollViewer {
					CanContentScroll = true,
					HorizontalScrollBarVisibility = ScrollBarVisibility.Auto,
					VerticalScrollBarVisibility = ScrollBarVisibility.Auto,
					Content = ViewObject,
					Focusable = true,
				};
			};

			if (uiObjRef == null)
				uiObjRef = new WeakReference(newObj);
			else
				uiObjRef.Target = newObj;
			return newObj;
		}
Exemplo n.º 2
0
		public override bool View(DecompilerTextView textView)
		{
			AvalonEditTextOutput output = new AvalonEditTextOutput();
			IHighlightingDefinition highlighting = null;
			
			textView.RunWithCancellation(
				token => Task.Factory.StartNew(
					() => {
						try {
							// cache read XAML because stream will be closed after first read
							if (xml == null) {
								using (var reader = new StreamReader(Data)) {
									xml = reader.ReadToEnd();
								}
							}
							output.Write(xml);
							highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
						}
						catch (Exception ex) {
							output.Write(ex.ToString());
						}
						return output;
					}, token)
			).Then(t => textView.ShowNode(t, this, highlighting)).HandleExceptions();
			return true;
		}
Exemplo n.º 3
0
 public override bool View(DecompilerTextView textView)
 {
   try
   {
     AvalonEditTextOutput output = new AvalonEditTextOutput();
     Data.Position = 0;
     IconBitmapDecoder decoder = new IconBitmapDecoder(Data, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.None);
     foreach (var frame in decoder.Frames)
     {
       output.Write(String.Format("{0}x{1}, {2} bit: ", frame.PixelHeight, frame.PixelWidth, frame.Thumbnail.Format.BitsPerPixel));
       AddIcon(output, frame);
       output.WriteLine();
     }
     output.AddButton(Images.Save, "Save", delegate
     {
       Save(null);
     });
     textView.ShowNode(output, this);
     return true;
   }
   catch (Exception)
   {
     return false;
   }
 }
Exemplo n.º 4
0
		static bool JumpToStatement(MethodDef method, uint ilOffset, DecompilerTextView textView) {
			if (method == null)
				return false;
			var serMod = method.Module.ToSerializedDnSpyModule();
			var key = new SerializedDnSpyToken(serMod, method.MDToken);
			if (textView == null)
				textView = MainWindow.Instance.SafeActiveTextView;

			bool found = MainWindow.Instance.DnSpyFileListTreeNode.FindModuleNode(method.Module) != null;
			if (found) {
				return MainWindow.Instance.JumpToReference(textView, method, (success, hasMovedCaret) => {
					if (success)
						return MoveCaretTo(textView, key, ilOffset);
					return false;
				});
			}

			MainWindow.Instance.Dispatcher.BeginInvoke(DispatcherPriority.Background, new Action(() => {
				MainWindow.Instance.JumpToReference(textView, method, (success, hasMovedCaret) => {
					if (success)
						return MoveCaretTo(textView, key, ilOffset);
					return false;
				});
			}));
			return true;
		}
Exemplo n.º 5
0
        // yuehan start: 保存 baml 到 xaml 文件
        public override bool Save(DecompilerTextView textView)
        {
            SaveFileDialog dlg = new SaveFileDialog();
            dlg.FileName = Path.GetFileName(DecompilerTextView.CleanUpName(base.Text as string));
            dlg.FileName = Regex.Replace(dlg.FileName, @"\.baml$", ".xaml", RegexOptions.IgnoreCase);
            if (dlg.ShowDialog() == true)
            {
                // 反编译 baml 文件
                var baml = this.Data;
                var asm = this.Ancestors().OfType<AssemblyTreeNode>().FirstOrDefault().LoadedAssembly;
                baml.Position = 0;
                var doc = LoadIntoDocument(asm.GetAssemblyResolver(), asm.AssemblyDefinition, baml);
                var xaml = doc.ToString();

                // 保存 xaml
                FileInfo fi = new FileInfo(dlg.FileName);
                if (fi.Exists) fi.Delete();

                using (var fs = fi.OpenWrite())
                using (StreamWriter sw = new StreamWriter(fs, Encoding.UTF8))
                {
                    sw.BaseStream.Seek(0, SeekOrigin.Begin);
                    sw.Write(xaml);
                    sw.Flush();
                    sw.Close();
                }
            }
            return true;
        }
Exemplo n.º 6
0
		public override bool View(DecompilerTextView textView)
		{
			try {
				AvalonEditTextOutput output = new AvalonEditTextOutput();
				Data.Position = 0;
				BitmapImage image = new BitmapImage();

				//HACK: windows imaging does not understand that .cur files have the same layout as .ico
				// so load to data, and modify the ResourceType in the header to make look like an icon...
				byte[] curData = ((MemoryStream)Data).ToArray();
				curData[2] = 1;
				using (Stream stream = new MemoryStream(curData)) {
					image.BeginInit();
					image.StreamSource = stream;
					image.EndInit();
				}

				output.AddUIElement(() => new Image { Source = image });
				output.WriteLine();
				output.AddButton(Images.Save, "Save", delegate {
					Save(null);
				});
				textView.ShowNode(output, this, null);
				return true;
			}
			catch (Exception) {
				return false;
			}
		}
Exemplo n.º 7
0
		public static int GetLineNumber(IBookmark b, DecompilerTextView textView)
		{
			var bm = b as BookmarkBase;
			if (bm != null)
				return bm.GetLineNumber(textView);
			return b.LineNumber;
		}
Exemplo n.º 8
0
		static IMemberRef GetMemberRef(DecompilerTextView textView)
		{
			if (textView == null)
				return null;

			var refSeg = textView.GetCurrentReferenceSegment();
			return refSeg == null ? null : refSeg.Reference as IMemberRef;
		}
Exemplo n.º 9
0
 public static bool JumpTo(DecompilerTextView textView, IMemberRef mr, MethodKey key, int ilOffset)
 {
     return MainWindow.Instance.JumpToReference(textView, mr, (success, hasMovedCaret) => {
         if (success)
             return MoveCaretTo(textView, key, ilOffset);
         return false;
     });
 }
Exemplo n.º 10
0
		public ITextMarker CreateMarker(DecompilerTextView textView, ITextMarkerService markerService) {
			var marker = CreateMarkerInternal(markerService, textView);
			var cm = textView == null ? null : textView.CodeMappings;
			marker.ZOrder = ZOrder;
			marker.IsVisible = b => cm != null && cm.ContainsKey(MethodKey);
			marker.TextMarkerObject = this;
			Initialize(textView, markerService, marker);
			return marker;
		}
Exemplo n.º 11
0
			public override bool IsVisible(DecompilerTextView textView) {
				TextLocation location, endLocation;
				var cm = textView == null ? null : textView.CodeMappings;
				if (cm == null || !cm.ContainsKey(MethodKey))
					return false;
				if (!cm[MethodKey].GetInstructionByTokenAndOffset(ILOffset, out location, out endLocation))
					return false;

				return true;
			}
Exemplo n.º 12
0
 public static bool JumpToReference(DecompilerTextView textView, IMemberRef mr, Func<TextLocation> getLocation)
 {
     bool retVal = MainWindow.Instance.JumpToReference(textView, mr, getLocation);
     if (!retVal) {
         MainWindow.Instance.ShowMessageBox(
             string.Format("Could not find {0}\n" +
             "Make sure that it's visible in the treeview and not a hidden method or part of a hidden class. You could also try to debug the method in IL mode.", mr));
     }
     return retVal;
 }
Exemplo n.º 13
0
		public static TextViewContext Create(SharpTreeView treeView = null, DecompilerTextView textView = null)
		{
			var reference = textView != null ? textView.GetReferenceSegmentAtMousePosition() : null;
			var selectedTreeNodes = treeView != null ? treeView.GetTopLevelSelection().ToArray() : null;
			return new TextViewContext {
				TreeView = treeView,
				SelectedTreeNodes = selectedTreeNodes,
				TextView = textView,
				Reference = reference
			};
		}
Exemplo n.º 14
0
		public override bool Save(DecompilerTextView textView)
		{
			SaveFileDialog dlg = new SaveFileDialog();
			dlg.FileName = Path.GetFileName(DecompilerTextView.CleanUpName(key));
			if (dlg.ShowDialog() == true) {
				data.Position = 0;
				using (var fs = dlg.OpenFile()) {
					data.CopyTo(fs);
				}
			}
			return true;
		}
Exemplo n.º 15
0
		public TextMarkerService(DecompilerTextView textView) {
			if (textView == null)
				throw new ArgumentNullException("textView");
			this.textView = textView;
			TextView.DocumentChanged += OnDocumentChanged;
			TextLineObjectManager.Instance.OnListModified += TextLineObjectManager_OnListModified;
			MainWindow.Instance.ExecuteWhenLoaded(() => {
				MainWindow.Instance.OnTabStateRemoved += OnTabStateRemoved;
				this.textView.OnShowOutput += textView_OnShowOutput;
				RecreateMarkers();
			});
			OnDocumentChanged(null, null);
		}
Exemplo n.º 16
0
 public static bool JumpToCurrentStatement(DecompilerTextView textView)
 {
     if (textView == null)
         return false;
     var info = DebugInformation.DebugStepInformation;
     if (info == null)
         return false;
     return MainWindow.Instance.JumpToReference(textView, info.Item3, (success, hasMovedCaret) => {
         if (success)
             return MoveCaretToCurrentStatement(textView);
         return false;
     });
 }
Exemplo n.º 17
0
        public IconBarMargin(IconBarManager manager, DecompilerTextView decompilerTextView)
        {
            this.decompilerTextView = decompilerTextView;
            BookmarkManager.Added += OnBookmarkAdded;
            BookmarkManager.Removed += OnBookmarkRemoved;
            decompilerTextView.OnShowOutput += decompilerTextView_OnShowOutput;
            MainWindow.Instance.ExecuteWhenLoaded(() => {
                MainWindow.Instance.OnTabStateRemoved += OnTabStateRemoved;
            });

            this.manager = manager;
            SyncBookmarks();
        }
		public override bool View(DecompilerTextView textView) {
			if (resElem.ResourceData.Code == ResourceTypeCode.String) {
				var output = new AvalonEditTextOutput();
				output.Write((string)((BuiltInResourceData)resElem.ResourceData).Data, TextTokenType.Text);
				textView.ShowNode(output, this, null);
				return true;
			}
			if (resElem.ResourceData.Code == ResourceTypeCode.ByteArray || resElem.ResourceData.Code == ResourceTypeCode.Stream) {
				var data = (byte[])((BuiltInResourceData)resElem.ResourceData).Data;
				return ResourceTreeNode.View(this, textView, new MemoryStream(data), Name);
			}

			return base.View(textView);
		}
Exemplo n.º 19
0
		protected override void Initialize(DecompilerTextView textView, ITextMarkerService markerService, ITextMarker marker) {
			marker.HighlightingColor = () => {
				switch (type) {
				case StackFrameLineType.CurrentStatement:
					return DebuggerColors.StackFrameCurrentHighlightingColor;
				case StackFrameLineType.SelectedReturnStatement:
					return DebuggerColors.StackFrameSelectedHighlightingColor;
				case StackFrameLineType.ReturnStatement:
					return DebuggerColors.StackFrameReturnHighlightingColor;
				default:
					throw new InvalidOperationException();
				}
			};
		}
Exemplo n.º 20
0
		public static bool JumpToStatement(MethodDef method, uint ilOffset, DecompilerTextView textView = null) {
			if (method == null)
				return false;
			var key = MethodKey.Create(method);
			if (key == null)
				return false;
			if (textView == null)
				textView = MainWindow.Instance.SafeActiveTextView;
			return MainWindow.Instance.JumpToReference(textView, method, (success, hasMovedCaret) => {
				if (success)
					return MoveCaretTo(textView, key.Value, ilOffset);
				return false;
			});
		}
Exemplo n.º 21
0
		public static void Display(DecompilerTextView textView) {
			AvalonEditTextOutput output = new AvalonEditTextOutput();
			output.WriteLine(string.Format("dnSpy version {0}", currentVersion.ToString()), TextTokenType.Text);
			var decVer = typeof(ICSharpCode.Decompiler.Ast.AstBuilder).Assembly.GetName().Version;
			output.WriteLine(string.Format("ILSpy Decompiler version {0}.{1}.{2}", decVer.Major, decVer.Minor, decVer.Build), TextTokenType.Text);
			if (checkForUpdateCode)
				output.AddUIElement(
					delegate {
						StackPanel stackPanel = new StackPanel();
						stackPanel.HorizontalAlignment = HorizontalAlignment.Center;
						stackPanel.Orientation = Orientation.Horizontal;
						if (latestAvailableVersion == null) {
							AddUpdateCheckButton(stackPanel, textView);
						}
						else {
						// we already retrieved the latest version sometime earlier
						ShowAvailableVersion(latestAvailableVersion, stackPanel);
						}
						CheckBox checkBox = new CheckBox();
						checkBox.Margin = new Thickness(4);
						checkBox.Content = "Automatically check for updates every week";
						UpdateSettings settings = new UpdateSettings(DNSpySettings.Load());
						checkBox.SetBinding(CheckBox.IsCheckedProperty, new Binding("AutomaticUpdateCheckEnabled") { Source = settings });
						return new StackPanel {
							Margin = new Thickness(0, 4, 0, 0),
							Cursor = Cursors.Arrow,
							Children = { stackPanel, checkBox }
						};
					});
			if (checkForUpdateCode)
				output.WriteLine();
			foreach (var plugin in App.CompositionContainer.GetExportedValues<IAboutPageAddition>())
				plugin.Write(output);
			output.WriteLine();
			using (Stream s = typeof(AboutPage).Assembly.GetManifestResourceStream(typeof(dnSpy.StartUpClass), "README.txt")) {
				using (StreamReader r = new StreamReader(s)) {
					string line;
					while ((line = r.ReadLine()) != null) {
						output.WriteLine(line, TextTokenType.Text);
					}
				}
			}
			output.AddVisualLineElementGenerator(new MyLinkElementGenerator("SharpDevelop", "http://www.icsharpcode.net/opensource/sd/"));
			output.AddVisualLineElementGenerator(new MyLinkElementGenerator("MIT License", "resource:license.txt"));
			output.AddVisualLineElementGenerator(new MyLinkElementGenerator("LGPL", "resource:LGPL.txt"));
			output.AddVisualLineElementGenerator(new MyLinkElementGenerator("COPYING", "resource:COPYING"));
			textView.ShowText(output);
			MainWindow.Instance.SetTitle(textView, "About");
		}
Exemplo n.º 22
0
		public static void Execute(DecompilerTextView textView) {
			if (!CanExecute(textView))
				return;

			var copier = new InstructionILBytesCopier();
			var text = copier.Copy(FindInstructions(textView));
			if (text.Length > 0) {
				Clipboard.SetText(text);
				if (copier.FoundUnknownBytes) {
					MainWindow.Instance.ShowIgnorableMessageBox("instr: unknown bytes",
						"Some of the copied bytes are unknown because the method has been edited. New tokens and string offsets are only known once the file has been saved to disk.",
						MessageBoxButton.OK);
				}
			}
		}
Exemplo n.º 23
0
		public static bool MoveCaretTo(DecompilerTextView textView, SerializedDnSpyToken key, uint ilOffset) {
			if (textView == null)
				return false;

			Dictionary<SerializedDnSpyToken, MemberMapping> cm;
			if (!VerifyAndGetCurrentDebuggedMethod(textView, key, out cm))
				return false;

			TextLocation location, endLocation;
			if (!cm[key].GetInstructionByTokenAndOffset(ilOffset, out location, out endLocation))
				return false;

			textView.ScrollAndMoveCaretTo(location.Line, location.Column);
			return true;
		}
Exemplo n.º 24
0
		public static bool MoveCaretTo(DecompilerTextView textView, MethodKey key, uint ilOffset) {
			if (textView == null)
				return false;
			TextLocation location, endLocation;
			var cm = textView.CodeMappings;
			if (cm == null || !cm.ContainsKey(key))
				return false;
			if (!cm[key].GetInstructionByTokenAndOffset(ilOffset, out location, out endLocation)) {
				//TODO: Missing IL ranges
				return false;
			}
			else {
				textView.ScrollAndMoveCaretTo(location.Line, location.Column);
				return true;
			}
		}
Exemplo n.º 25
0
		public static void Display(DecompilerTextView textView)
		{
			AvalonEditTextOutput output = new AvalonEditTextOutput();
			output.WriteLine("ILSpy version " + RevisionClass.FullVersion);
			output.AddUIElement(
				delegate {
					StackPanel stackPanel = new StackPanel();
					stackPanel.HorizontalAlignment = HorizontalAlignment.Center;
					stackPanel.Orientation = Orientation.Horizontal;
					if (latestAvailableVersion == null) {
						AddUpdateCheckButton(stackPanel, textView);
					} else {
						// we already retrieved the latest version sometime earlier
						ShowAvailableVersion(latestAvailableVersion, stackPanel);
					}
					CheckBox checkBox = new CheckBox();
					checkBox.Margin = new Thickness(4);
					checkBox.Content = "Automatically check for updates every week";
					UpdateSettings settings = new UpdateSettings(ILSpySettings.Load());
					checkBox.SetBinding(CheckBox.IsCheckedProperty, new Binding("AutomaticUpdateCheckEnabled") { Source = settings });
					return new StackPanel {
						Margin = new Thickness(0, 4, 0, 0),
						Cursor = Cursors.Arrow,
						Children = { stackPanel, checkBox }
					};
				});
			output.WriteLine();
			foreach (var plugin in App.CompositionContainer.GetExportedValues<IAboutPageAddition>())
				plugin.Write(output);
			output.WriteLine();
			using (Stream s = typeof(AboutPage).Assembly.GetManifestResourceStream(typeof(AboutPage), "README.txt")) {
				using (StreamReader r = new StreamReader(s)) {
					string line;
					while ((line = r.ReadLine()) != null) {
						output.WriteLine(line);
					}
				}
			}
			output.AddVisualLineElementGenerator(new MyLinkElementGenerator("SharpDevelop", "http://www.icsharpcode.net/opensource/sd/"));
			output.AddVisualLineElementGenerator(new MyLinkElementGenerator("MIT License", "resource:license.txt"));
			output.AddVisualLineElementGenerator(new MyLinkElementGenerator("LGPL", "resource:LGPL.txt"));
			textView.ShowText(output);
			
			//reset icon bar
			textView.manager.Bookmarks.Clear();
		}
Exemplo n.º 26
0
		public bool GetLocation(DecompilerTextView textView, out TextLocation location, out TextLocation endLocation) {
			var cm = textView == null ? null : textView.CodeMappings;
			MemberMapping mapping;
			if (cm == null || !cm.TryGetValue(methodKey, out mapping)) {
				location = endLocation = new TextLocation();
				return false;
			}

			bool isMatch;
			SourceCodeMapping map = mapping.GetInstructionByOffset(ilOffset, out isMatch);
			if (map == null) {
				location = endLocation = new TextLocation();
				return false;
			}

			location = map.StartLocation;
			endLocation = map.EndLocation;
			return true;
		}
Exemplo n.º 27
0
		static IEnumerable<ReferenceSegment> FindInstructions(DecompilerTextView textView) {
			if (textView.textEditor.SelectionLength <= 0)
				yield break;
			int start = textView.textEditor.SelectionStart;
			int end = start + textView.textEditor.SelectionLength;

			var refs = textView.References;
			if (refs == null)
				yield break;
			var r = refs.FindFirstSegmentWithStartAfter(start);
			while (r != null) {
				if (r.StartOffset >= end)
					break;
				if (r.IsLocalTarget && r.Reference is InstructionReference)
					yield return r;

				r = refs.GetNextSegment(r);
			}
		}
Exemplo n.º 28
0
		public static TextViewContext Create(SharpTreeView treeView = null, DecompilerTextView textView = null, ListBox listBox = null)
		{
			ReferenceSegment reference;
			if (textView != null)
				reference = textView.GetReferenceSegmentAtMousePosition();
			else if (listBox != null)
				reference = new ReferenceSegment { Reference = ((SearchResult)listBox.SelectedItem).Member };
			else
				reference = null;
			var position = textView != null ? textView.GetPositionFromMousePosition() : null;
			var selectedTreeNodes = treeView != null ? treeView.GetTopLevelSelection().ToArray() : null;
			return new TextViewContext {
				TreeView = treeView,
				SelectedTreeNodes = selectedTreeNodes,
				TextView = textView,
				Reference = reference,
				Position = position
			};
		}
Exemplo n.º 29
0
		public override bool View(DecompilerTextView textView)
		{
			IHighlightingDefinition highlighting = null;
			
			textView.RunWithCancellation(
				token => Task.Factory.StartNew(
					() => {
						AvalonEditTextOutput output = new AvalonEditTextOutput();
						try {
							if (LoadBaml(output))
								highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
						} catch (Exception ex) {
							output.Write(ex.ToString());
						}
						return output;
					}, token))
				.Then(output => textView.ShowNode(output, this, highlighting))
				.HandleExceptions();
			return true;
		}
Exemplo n.º 30
0
		public override bool View(DecompilerTextView textView)
		{
			try {
				AvalonEditTextOutput output = new AvalonEditTextOutput();
				Data.Position = 0;
				BitmapImage image = new BitmapImage();
				image.BeginInit();
				image.StreamSource = Data;
				image.EndInit();
				output.AddUIElement(() => new Image { Source = image });
				output.WriteLine();
				output.AddButton(Images.Save, "Save", delegate {
					Save(null);
				});
				textView.ShowNode(output, this);
				return true;
			}
			catch (Exception) {
				return false;
			}
		}