Text output implementation for AvalonEdit.
Наследование: ISmartTextOutput
Пример #1
0
 public override void Execute(object parameter)
 {
     MainWindow.Instance.TextView.RunWithCancellation(ct => Task<AvalonEditTextOutput>.Factory.StartNew(() => {
         AvalonEditTextOutput output = new AvalonEditTextOutput();
         Parallel.ForEach(MainWindow.Instance.CurrentAssemblyList.GetAssemblies(), new ParallelOptions { MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = ct }, delegate(LoadedAssembly asm) {
             if (!asm.HasLoadError) {
                 Stopwatch w = Stopwatch.StartNew();
                 Exception exception = null;
                 using (var writer = new System.IO.StreamWriter("c:\\temp\\decompiled\\" + asm.ShortName + ".cs")) {
                     try {
                         new CSharpLanguage().DecompileAssembly(asm, new Decompiler.PlainTextOutput(writer), new DecompilationOptions { FullDecompilation = true, CancellationToken = ct });
                     }
                     catch (Exception ex) {
                         writer.WriteLine(ex.ToString());
                         exception = ex;
                     }
                 }
                 lock (output) {
                     output.Write(asm.ShortName + " - " + w.Elapsed);
                     if (exception != null) {
                         output.Write(" - ");
                         output.Write(exception.GetType().Name);
                     }
                     output.WriteLine();
                 }
             }
         });
         return output;
     }, ct), task => MainWindow.Instance.TextView.ShowText(task.Result));
 }
Пример #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;
		}
Пример #3
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;
			}
		}
Пример #4
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;
   }
 }
Пример #5
0
		bool LoadBaml(AvalonEditTextOutput output)
		{
			var asm = this.Ancestors().OfType<AssemblyTreeNode>().FirstOrDefault().LoadedAssembly;
			Data.Position = 0;
			XDocument xamlDocument = LoadIntoDocument(asm.GetAssemblyResolver(), asm.AssemblyDefinition, Data);
			output.Write(xamlDocument.ToString());
			return true;
		}
		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);
		}
Пример #7
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");
		}
Пример #8
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();
		}
Пример #9
0
 void TreeView_SelectionChanged(object sender, SelectionChangedEventArgs e)
 {
    this.textEditor.Clear();
    AvalonEditTextOutput textOutput = new AvalonEditTextOutput();
    //_humDisassembler = new HumanizerDisassembler(textOutput, token);
    foreach (var item in MainWindow.Instance.SelectedNodes)
    {
       var typeTreeNode = item as TypeTreeNode;
       if (typeTreeNode != null)
       {
          ToolSetSettings.Instance.Language.DecompileType(typeTreeNode.TypeDefinition, textOutput, new DecompilationOptions());
          //_humDisassembler.DisassembleType(typeTreeNode.TypeDefinition);
       }
    }
    this.textEditor.SyntaxHighlighting = ToolSetSettings.Instance.Language.SyntaxHighlighting;
    this.textEditor.AppendText(textOutput.GetDocument().Text);
    textEditor.TextArea.DefaultInputHandler.NestedInputHandlers.Add(new ICSharpCode.AvalonEdit.Search.SearchInputHandler(textEditor.TextArea));
 }
Пример #10
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;
		}
Пример #11
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(ImageCache.Instance.GetImage("Save", BackgroundType.Button), "Save", delegate {
             Save(null);
         });
         textView.ShowNode(output, this);
         return true;
     }
     catch (Exception) {
         return false;
     }
 }
Пример #12
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();
     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);
         }
     }
     textView.Show(output);
 }
Пример #13
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...
                MemoryStream s = Data as MemoryStream;
                if (null == s)
                {
                    // data was stored in another stream type (e.g. PinnedBufferedMemoryStream)
                    s = new MemoryStream();
                    Data.CopyTo(s);
                }
                byte[] curData = s.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(ImageCache.Instance.GetImage("Save", BackgroundType.Button), "Save", delegate {
                    Save(null);
                });
                textView.ShowNode(output, this);
                return true;
            }
            catch (Exception) {
                return false;
            }
        }
Пример #14
0
		internal override bool View(DecompilerTextView textView)
		{
			EmbeddedResource er = r as EmbeddedResource;
			if (er != null) {
				Stream s = er.GetResourceStream();
				if (s != null && s.Length < DecompilerTextView.DefaultOutputLengthLimit) {
					s.Position = 0;
					FileType type = GuessFileType.DetectFileType(s);
					if (type != FileType.Binary) {
						s.Position = 0;
						AvalonEditTextOutput output = new AvalonEditTextOutput();
						output.Write(FileReader.OpenStream(s, Encoding.UTF8).ReadToEnd());
						string ext;
						if (type == FileType.Xml)
							ext = ".xml";
						else
							ext = Path.GetExtension(DecompilerTextView.CleanUpName(er.Name));
						textView.Show(output, HighlightingManager.Instance.GetDefinitionByExtension(ext));
						return true;
					}
				}
			}
			return false;
		}
Пример #15
0
		public override bool View(DecompilerTextView textView) {
			AvalonEditTextOutput output = new AvalonEditTextOutput();
			IHighlightingDefinition highlighting = null;
			var lang = MainWindow.Instance.CurrentLanguage;

			textView.RunWithCancellation(
				token => Task.Factory.StartNew(
					() => {
						try {
							bamlData.Position = 0;
							var document = BamlReader.ReadDocument(bamlData, token);
							if (BamlSettings.Instance.DisassembleBaml)
								Disassemble(module, document, lang, output, out highlighting, token);
							else
								Decompile(module, document, lang, output, out highlighting, token);
						}
						catch (Exception ex) {
							output.Write(ex.ToString(), TextTokenType.Text);
						}
						return output;
					}, token)
				).Then(t => textView.ShowNode(t, this, highlighting)).HandleExceptions();
			return true;
		}
Пример #16
0
        internal override bool View(DecompilerTextView textView)
        {
            AvalonEditTextOutput output = new AvalonEditTextOutput();
            IHighlightingDefinition highlighting = null;

            if (LoadImage(output)) {
                textView.Show(output, highlighting);
            } else {
                textView.RunWithCancellation(
                    token => Task.Factory.StartNew(
                        () => {
                            try {
                                if (LoadBaml(output))
                                    highlighting = HighlightingManager.Instance.GetDefinitionByExtension(".xml");
                            } catch (Exception ex) {
                                output.Write(ex.ToString());
                            }
                            return output;
                        }),
                    t => textView.Show(t.Result, highlighting)
                );
            }
            return true;
        }
Пример #17
0
		static void AddUpdateCheckButton(StackPanel stackPanel, DecompilerTextView textView) {
			Button button = new Button();
			button.Content = "Check for updates";
			button.Cursor = Cursors.Arrow;
			stackPanel.Children.Add(button);

			button.Click += delegate {
				button.Content = "Checking...";
				button.IsEnabled = false;
				GetLatestVersionAsync().ContinueWith(
					delegate (Task<AvailableVersionInfo> task) {
						try {
							stackPanel.Children.Clear();
							ShowAvailableVersion(task.Result, stackPanel);
						}
						catch (Exception ex) {
							AvalonEditTextOutput exceptionOutput = new AvalonEditTextOutput();
							exceptionOutput.WriteLine(ex.ToString(), TextTokenType.Text);
							textView.ShowText(exceptionOutput);
						}
					}, TaskScheduler.FromCurrentSynchronizationContext());
			};
		}
Пример #18
0
 public void ShowNode(AvalonEditTextOutput textOutput, ILSpyTreeNode node, IHighlightingDefinition highlighting = null)
 {
     ShowNodes(textOutput, new[] { node }, highlighting);
 }
Пример #19
0
        /// <summary>
        /// Switches the GUI into "waiting" mode, then calls <paramref name="taskCreation"/> to create
        /// the task.
        /// If another task is started before the previous task finishes running, the previous task is cancelled.
        /// </summary>
        public Task <T> RunWithCancellation <T>(Func <CancellationToken, Task <T> > taskCreation)
        {
            if (waitAdorner.Visibility != Visibility.Visible)
            {
                waitAdorner.Visibility = Visibility.Visible;
                // Work around a WPF bug by setting IsIndeterminate only while the progress bar is visible.
                // https://github.com/icsharpcode/ILSpy/issues/593
                progressBar.IsIndeterminate = true;
                waitAdorner.BeginAnimation(OpacityProperty, new DoubleAnimation(0, 1, new Duration(TimeSpan.FromSeconds(0.5)), FillBehavior.Stop));
                var taskBar = MainWindow.Instance.TaskbarItemInfo;
                if (taskBar != null)
                {
                    taskBar.ProgressState = System.Windows.Shell.TaskbarItemProgressState.Indeterminate;
                }
            }
            CancellationTokenSource previousCancellationTokenSource = currentCancellationTokenSource;
            var myCancellationTokenSource = new CancellationTokenSource();

            currentCancellationTokenSource = myCancellationTokenSource;
            // cancel the previous only after current was set to the new one (avoid that the old one still finishes successfully)
            if (previousCancellationTokenSource != null)
            {
                previousCancellationTokenSource.Cancel();
            }

            var      tcs = new TaskCompletionSource <T>();
            Task <T> task;

            try {
                task = taskCreation(myCancellationTokenSource.Token);
            } catch (OperationCanceledException) {
                task = TaskHelper.FromCancellation <T>();
            } catch (Exception ex) {
                task = TaskHelper.FromException <T>(ex);
            }
            Action continuation = delegate {
                try {
                    if (currentCancellationTokenSource == myCancellationTokenSource)
                    {
                        currentCancellationTokenSource = null;
                        waitAdorner.Visibility         = Visibility.Collapsed;
                        progressBar.IsIndeterminate    = false;
                        var taskBar = MainWindow.Instance.TaskbarItemInfo;
                        if (taskBar != null)
                        {
                            taskBar.ProgressState = System.Windows.Shell.TaskbarItemProgressState.None;
                        }
                        if (task.IsCanceled)
                        {
                            AvalonEditTextOutput output = new AvalonEditTextOutput();
                            output.WriteLine("The operation was canceled.");
                            ShowOutput(output);
                        }
                        tcs.SetFromTask(task);
                    }
                    else
                    {
                        tcs.SetCanceled();
                    }
                } finally {
                    myCancellationTokenSource.Dispose();
                }
            };

            task.ContinueWith(delegate { Dispatcher.BeginInvoke(DispatcherPriority.Normal, continuation); });
            return(tcs.Task);
        }
Пример #20
0
		bool LoadBaml(AvalonEditTextOutput output)
		{
			var asm = this.Ancestors().OfType<AssemblyTreeNode>().FirstOrDefault().LoadedAssembly;
			
			AppDomain bamlDecompilerAppDomain = null;
			try {
				BamlDecompiler decompiler = CreateBamlDecompilerInAppDomain(ref bamlDecompilerAppDomain, asm.FileName);
				
				MemoryStream bamlStream = new MemoryStream();
				data.Position = 0;
				data.CopyTo(bamlStream);
				
				output.Write(decompiler.DecompileBaml(bamlStream, asm.FileName));
				return true;
			} finally {
				if (bamlDecompilerAppDomain != null)
					AppDomain.Unload(bamlDecompilerAppDomain);
			}
		}
Пример #21
0
		void Window_RequestNavigate(object sender, RequestNavigateEventArgs e)
		{
			if (e.Uri.Scheme == "resource") {
				AvalonEditTextOutput output = new AvalonEditTextOutput();
				using (Stream s = typeof(App).Assembly.GetManifestResourceStream(typeof(dnSpy.StartUpClass), e.Uri.AbsolutePath)) {
					using (StreamReader r = new StreamReader(s)) {
						string line;
						while ((line = r.ReadLine()) != null) {
							output.Write(line, TextTokenType.Text);
							output.WriteLine();
						}
					}
				}
				var textView = ILSpy.MainWindow.Instance.SafeActiveTextView;
				textView.ShowText(output);
				ILSpy.MainWindow.Instance.SetTitle(textView, e.Uri.AbsolutePath);
				e.Handled = true;
			}
		}
Пример #22
0
		internal 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.Show(output, null);
				return true;
			} catch (Exception) {
				return false;
			}
		}
Пример #23
0
		void MainWindow_Loaded(object sender, RoutedEventArgs e)
		{
			ILSpySettings spySettings = this.spySettings;
			this.spySettings = null;
			
			// Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
			// This makes the UI come up a bit faster.
			this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);
			
			HandleCommandLineArguments(App.CommandLineArguments);
			
			if (assemblyList.GetAssemblies().Length == 0
				&& assemblyList.ListName == AssemblyListManager.DefaultListName)
			{
				LoadInitialAssemblies();
			}
			
			ShowAssemblyList(this.assemblyList);
			
			HandleCommandLineArgumentsAfterShowList(App.CommandLineArguments);
			if (App.CommandLineArguments.NavigateTo == null && App.CommandLineArguments.AssembliesToLoad.Count != 1) {
				SharpTreeNode node = null;
				if (sessionSettings.ActiveTreeViewPath != null) {
					node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
					if (node == this.assemblyListTreeNode & sessionSettings.ActiveAutoLoadedAssembly != null) {
						this.assemblyList.OpenAssembly(sessionSettings.ActiveAutoLoadedAssembly, true);
						node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
					}
				}
				if (node != null) {
					SelectNode(node);
					
					// only if not showing the about page, perform the update check:
					ShowMessageIfUpdatesAvailableAsync(spySettings);
				} else {
					AboutPage.Display(decompilerTextView);
				}
			}
			
			AvalonEditTextOutput output = new AvalonEditTextOutput();
			if (FormatExceptions(App.StartupExceptions.ToArray(), output))
				decompilerTextView.ShowText(output);
		}
Пример #24
0
		void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args) {
			if (args.NavigateTo != null) {
				bool found = false;
				if (args.NavigateTo.StartsWith("N:", StringComparison.Ordinal)) {
					string namespaceName = args.NavigateTo.Substring(2);
					foreach (DnSpyFile asm in commandLineLoadedFiles) {
						AssemblyTreeNode asmNode = dnSpyFileListTreeNode.FindAssemblyNode(asm);
						if (asmNode != null) {
							NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName);
							if (nsNode != null) {
								found = true;
								SelectNode(nsNode);
								break;
							}
						}
					}
				}
				else {
					foreach (DnSpyFile asm in commandLineLoadedFiles) {
						ModuleDef def = asm.ModuleDef;
						if (def != null) {
							IMemberRef mr = XmlDocKeyProvider.FindMemberByKey(def, args.NavigateTo);
							if (mr != null) {
								found = true;
								JumpToReference(mr);
								break;
							}
						}
					}
				}
				if (!found) {
					AvalonEditTextOutput output = new AvalonEditTextOutput();
					output.Write(string.Format("Cannot find '{0}' in command line specified assemblies.", args.NavigateTo), TextTokenType.Text);
					SafeActiveTextView.ShowText(output);
				}
			}
			else if (commandLineLoadedFiles.Count == 1) {
				// NavigateTo == null and an assembly was given on the command-line:
				// Select the newly loaded assembly
				JumpToReference(commandLineLoadedFiles[0].ModuleDef);
			}
			if (args.Search != null) {
				SearchPane.Instance.SearchTerm = args.Search;
				SearchPane.Instance.Show();
			}
			if (!string.IsNullOrEmpty(args.SaveDirectory)) {
				foreach (var x in commandLineLoadedFiles)
					OnExportAssembly(x, args.SaveDirectory);
			}
			commandLineLoadedFiles.Clear(); // clear references once we don't need them anymore
		}
Пример #25
0
		void MainWindow_Loaded(object sender, RoutedEventArgs e)
		{
			ILSpySettings spySettings = this.spySettings;
			this.spySettings = null;
			
			// Load AssemblyList only in Loaded event so that WPF is initialized before we start the CPU-heavy stuff.
			// This makes the UI come up a bit faster.
			this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);
			
			HandleCommandLineArguments(App.CommandLineArguments);
			
			ShowAssemblyList(this.assemblyList);
			
			HandleCommandLineArgumentsAfterShowList(App.CommandLineArguments);
			if (App.CommandLineArguments.NavigateTo == null && App.CommandLineArguments.AssembliesToLoad.Count != 1) {
				SharpTreeNode node = FindNodeByPath(sessionSettings.ActiveTreeViewPath, true);
				if (node != null) {
					SelectNode(node);
					
					// only if not showing the about page, perform the update check:
					ShowMessageIfUpdatesAvailableAsync(spySettings);
				} else {
					AboutPage.Display(decompilerTextView);
				}
			}
			
			NavigationCommands.Search.InputGestures.Add(new KeyGesture(Key.E, ModifierKeys.Control));
			
			AvalonEditTextOutput output = new AvalonEditTextOutput();
			if (FormatExceptions(App.StartupExceptions.ToArray(), output))
				decompilerTextView.ShowText(output);
		}
Пример #26
0
 private static void AddUpdateCheckButton(StackPanel stackPanel, DecompilerTextView textView)
 {
     Button button = new Button();
     button.Content = "检查更新";
     button.Cursor = Cursors.Arrow;
     stackPanel.Children.Add(button);
     button.Click += delegate(object param0, RoutedEventArgs param1)
     {
         button.Content = "检查更新中...";
         button.IsEnabled = false;
         AboutPage.GetLatestVersionAsync().ContinueWith(delegate(Task<AboutPage.AvailableVersionInfo> task)
         {
             try
             {
                 stackPanel.Children.Clear();
                 AboutPage.ShowAvailableVersion(task.Result, stackPanel);
             }
             catch (Exception ex)
             {
                 AvalonEditTextOutput avalonEditTextOutput = new AvalonEditTextOutput();
                 avalonEditTextOutput.WriteLine(ex.ToString());
                 textView.ShowText(avalonEditTextOutput);
             }
         }, TaskScheduler.FromCurrentSynchronizationContext());
     };
 }
Пример #27
0
 private static void AddIcon(AvalonEditTextOutput output, BitmapFrame frame)
 {
   output.AddUIElement(() => new Image { Source = frame });
 }
Пример #28
0
 public void ShowText(AvalonEditTextOutput textOutput)
 {
     ShowNodes(textOutput, null);
 }
Пример #29
0
		void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args)
		{
			if (args.NavigateTo != null) {
				bool found = false;
				if (args.NavigateTo.StartsWith("N:", StringComparison.Ordinal)) {
					string namespaceName = args.NavigateTo.Substring(2);
					foreach (LoadedAssembly asm in commandLineLoadedAssemblies) {
						AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(asm);
						if (asmNode != null) {
							NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName);
							if (nsNode != null) {
								found = true;
								SelectNode(nsNode);
								break;
							}
						}
					}
				} else {
					foreach (LoadedAssembly asm in commandLineLoadedAssemblies) {
						ModuleDefinition def = asm.ModuleDefinition;
						if (def != null) {
							MemberReference mr = XmlDocKeyProvider.FindMemberByKey(def, args.NavigateTo);
							if (mr != null) {
								found = true;
								JumpToReference(mr);
								break;
							}
						}
					}
				}
				if (!found) {
					AvalonEditTextOutput output = new AvalonEditTextOutput();
					output.Write(string.Format("Cannot find '{0}' in command line specified assemblies.", args.NavigateTo));
					decompilerTextView.ShowText(output);
				}
			} else if (commandLineLoadedAssemblies.Count == 1) {
				// NavigateTo == null and an assembly was given on the command-line:
				// Select the newly loaded assembly
				JumpToReference(commandLineLoadedAssemblies[0].ModuleDefinition);
			}
			if (args.Search != null)
			{
				SearchPane.Instance.SearchTerm = args.Search;
				SearchPane.Instance.Show();
			}
			if (!string.IsNullOrEmpty(args.SaveDirectory)) {
				foreach (var x in commandLineLoadedAssemblies) {
					x.ContinueWhenLoaded( (Task<ModuleDefinition> moduleTask) => {
						OnExportAssembly(moduleTask, args.SaveDirectory);
					}, TaskScheduler.FromCurrentSynchronizationContext());
				}
			}
			commandLineLoadedAssemblies.Clear(); // clear references once we don't need them anymore
		}
Пример #30
0
		void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args)
		{
			if (args.NavigateTo != null) {
				bool found = false;
				if (args.NavigateTo.StartsWith("N:", StringComparison.Ordinal)) {
					string namespaceName = args.NavigateTo.Substring(2);
					foreach (LoadedAssembly asm in commandLineLoadedAssemblies) {
						AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(asm);
						if (asmNode != null) {
							NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName);
							if (nsNode != null) {
								found = true;
								SelectNode(nsNode);
								break;
							}
						}
					}
				} else {
					foreach (LoadedAssembly asm in commandLineLoadedAssemblies) {
						AssemblyDefinition def = asm.AssemblyDefinition;
						if (def != null) {
							MemberReference mr = XmlDocKeyProvider.FindMemberByKey(def.MainModule, args.NavigateTo);
							if (mr != null) {
								found = true;
								JumpToReference(mr);
								break;
							}
						}
					}
				}
				if (!found) {
					AvalonEditTextOutput output = new AvalonEditTextOutput();
					output.Write("Cannot find " + args.NavigateTo);
					decompilerTextView.ShowText(output);
				}
			}
			commandLineLoadedAssemblies.Clear(); // clear references once we don't need them anymore
		}
Пример #31
0
		void HandleCommandLineArgumentsAfterShowList(CommandLineArguments args)
		{
			if (args.NavigateTo != null) {
				bool found = false;
				if (args.NavigateTo.StartsWith("N:", StringComparison.Ordinal)) {
					string namespaceName = args.NavigateTo.Substring(2);
					foreach (LoadedAssembly asm in commandLineLoadedAssemblies) {
						AssemblyTreeNode asmNode = assemblyListTreeNode.FindAssemblyNode(asm);
						if (asmNode != null) {
							NamespaceTreeNode nsNode = asmNode.FindNamespaceNode(namespaceName);
							if (nsNode != null) {
								found = true;
								SelectNode(nsNode);
								break;
							}
						}
					}
				} else {
					foreach (LoadedAssembly asm in commandLineLoadedAssemblies) {
						ModuleDefinition def = asm.ModuleDefinition;
						if (def != null) {
							MemberReference mr = XmlDocKeyProvider.FindMemberByKey(def, args.NavigateTo);
							if (mr != null) {
								found = true;
								JumpToReference(mr);
								break;
							}
						}
					}
				}
				if (!found) {
					AvalonEditTextOutput output = new AvalonEditTextOutput();
					output.Write(string.Format("Cannot find '{0}' in command line specified assemblies.", args.NavigateTo));
					decompilerTextView.ShowText(output);
				}
			} else if (commandLineLoadedAssemblies.Count == 1) {
				// NavigateTo == null and an assembly was given on the command-line:
				// Select the newly loaded assembly
				JumpToReference(commandLineLoadedAssemblies[0].ModuleDefinition);
			}
			commandLineLoadedAssemblies.Clear(); // clear references once we don't need them anymore
		}
Пример #32
0
        void LoadingHandler(int i)
        {
            switch (i) {
            case 0:
                this.CommandBindings.Add(new CommandBinding(ILSpyTreeNode.TreeNodeActivatedEvent, TreeNodeActivatedExecuted));

                ContextMenuProvider.Add(treeView);

                ILSpySettings spySettings = this.spySettings;
                this.spySettings = null;

                this.assemblyList = assemblyListManager.LoadList(spySettings, sessionSettings.ActiveAssemblyList);
                break;

            case 1:
                HandleCommandLineArguments(App.CommandLineArguments);

                if (assemblyList.GetAssemblies().Length == 0
                    && assemblyList.ListName == AssemblyListManager.DefaultListName) {
                    LoadInitialAssemblies();
                }

                ShowAssemblyListDontAskUser(this.assemblyList);
                break;

            case 2:
                HandleCommandLineArgumentsAfterShowList(App.CommandLineArguments);
                if (App.CommandLineArguments.NavigateTo == null && App.CommandLineArguments.AssembliesToLoad.Count != 1) {
                    if (ICSharpCode.ILSpy.Options.DisplaySettingsPanel.CurrentDisplaySettings.RestoreTabsAtStartup) {
                        RestoreTabGroups(sessionSettings.SavedTabGroupsState);
                        if (!sessionSettings.TabsFound)
                            AboutPage.Display(SafeActiveTextView);
                    }
                    else {
                        AboutPage.Display(SafeActiveTextView);
                    }
                }
                break;

            case 3:
                AvalonEditTextOutput output = new AvalonEditTextOutput();
                if (FormatExceptions(App.StartupExceptions.ToArray(), output))
                    SafeActiveTextView.ShowText(output);

                if (topPane.Content == null) {
                    var pane = GetPane(topPane, sessionSettings.TopPaneSettings.Name);
                    if (pane != null)
                        ShowInTopPane(pane.PaneTitle, pane);
                }
                if (bottomPane.Content == null) {
                    var pane = GetPane(bottomPane, sessionSettings.BottomPaneSettings.Name);
                    if (pane != null)
                        ShowInBottomPane(pane.PaneTitle, pane);
                }
                break;

            case 4:
                foreach (var plugin in plugins)
                    plugin.OnLoaded();

                var list = callWhenLoaded;
                callWhenLoaded = null;
                foreach (var func in list)
                    func();

                break;

            case 5:
                this.IsEnabled = true;

                // Make sure that when no tabs are created that we have focus. If we don't do this we
                // can't press Ctrl+K and open the asm search.
                this.Focus();

                // Sometimes we get keyboard focus when it's better that the text editor gets the focus instead
                this.GotKeyboardFocus += MainWindow_GotKeyboardFocus;

                loadingControl.Visibility = Visibility.Collapsed;
                mainGrid.Visibility = Visibility.Visible;

                // In case a plugin has added their own bindings
                UninstallTabCommandBindings(ActiveTabState);
                InstallTabCommandBindings(ActiveTabState);

                // Flickering workaround fix. Could reproduce it when using VMWare + WinXP
                loadingProgressBar.IsIndeterminate = false;
                return;
            default:
                return;
            }
            StartLoadingHandler(i + 1);
        }
Пример #33
0
		void Window_RequestNavigate(object sender, RequestNavigateEventArgs e)
		{
			if (e.Uri.Scheme == "resource") {
				AvalonEditTextOutput output = new AvalonEditTextOutput();
				using (Stream s = typeof(App).Assembly.GetManifestResourceStream(typeof(App), e.Uri.AbsolutePath)) {
					using (StreamReader r = new StreamReader(s)) {
						string line;
						while ((line = r.ReadLine()) != null) {
							output.Write(line);
							output.WriteLine();
						}
					}
				}
				ILSpy.MainWindow.Instance.TextView.Show(output);
			} else {
				Process.Start(e.Uri.ToString());
			}
		}
Пример #34
0
        /// <summary>
        /// Shows the given output in the text view.
        /// </summary>
        void ShowOutput(AvalonEditTextOutput textOutput, IHighlightingDefinition highlighting = null, DecompilerTextViewState state = null)
        {
            Debug.WriteLine("Showing {0} characters of output", textOutput.TextLength);
            Stopwatch w = Stopwatch.StartNew();

            ClearLocalReferenceMarks();
            textEditor.ScrollToHome();
            if (foldingManager != null)
            {
                FoldingManager.Uninstall(foldingManager);
                foldingManager = null;
            }
            textEditor.Document                  = null; // clear old document while we're changing the highlighting
            uiElementGenerator.UIElements        = textOutput.UIElements;
            referenceElementGenerator.References = textOutput.References;
            references       = textOutput.References;
            definitionLookup = textOutput.DefinitionLookup;
            textEditor.SyntaxHighlighting = highlighting;

            // Change the set of active element generators:
            foreach (var elementGenerator in activeCustomElementGenerators)
            {
                textEditor.TextArea.TextView.ElementGenerators.Remove(elementGenerator);
            }
            activeCustomElementGenerators.Clear();

            foreach (var elementGenerator in textOutput.elementGenerators)
            {
                textEditor.TextArea.TextView.ElementGenerators.Add(elementGenerator);
                activeCustomElementGenerators.Add(elementGenerator);
            }

            Debug.WriteLine("  Set-up: {0}", w.Elapsed); w.Restart();
            textEditor.Document = textOutput.GetDocument();
            Debug.WriteLine("  Assigning document: {0}", w.Elapsed); w.Restart();
            if (textOutput.Foldings.Count > 0)
            {
                if (state != null)
                {
                    state.RestoreFoldings(textOutput.Foldings);
                    textEditor.ScrollToVerticalOffset(state.VerticalOffset);
                    textEditor.ScrollToHorizontalOffset(state.HorizontalOffset);
                }
                foldingManager = FoldingManager.Install(textEditor.TextArea);
                foldingManager.UpdateFoldings(textOutput.Foldings.OrderBy(f => f.StartOffset), -1);
                Debug.WriteLine("  Updating folding: {0}", w.Elapsed); w.Restart();
            }

            // update debugger info
            DebugInformation.CodeMappings = textOutput.DebuggerMemberMappings.ToDictionary(m => m.MetadataToken);

            // update class bookmarks
            var document = textEditor.Document;

            manager.Bookmarks.Clear();
            foreach (var pair in textOutput.DefinitionLookup.definitions)
            {
                MemberReference member = pair.Key as MemberReference;
                int             offset = pair.Value;
                if (member != null)
                {
                    int line = document.GetLocation(offset).Line;
                    manager.Bookmarks.Add(new MemberBookmark(member, line));
                }
            }
        }