Ejemplo n.º 1
0
        public static void Display(DecompilerTextView textView)
        {
            AvalonEditTextOutput output = new AvalonEditTextOutput()
            {
                EnableHyperlinks = true
            };

            output.WriteLine(Resources.ILSpyVersion + 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        = Resources.AutomaticallyCheckUpdatesEveryWeek;
                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.ExportProvider.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"));
            output.AddVisualLineElementGenerator(new MyLinkElementGenerator("MS-PL", "resource:MS-PL.txt"));
            textView.ShowText(output);
        }
        public void Execute(TextViewContext context)
        {
            // Get all assemblies in the selection that are stored inside a package.
            var selectedNodes = context.SelectedTreeNodes.OfType <AssemblyTreeNode>()
                                .Where(asm => asm.PackageEntry != null).ToArray();
            // Get root assembly to infer the initial directory for the save dialog.
            var bundleNode = selectedNodes.FirstOrDefault()?.Ancestors().OfType <AssemblyTreeNode>()
                             .FirstOrDefault(asm => asm.PackageEntry == null);

            if (bundleNode == null)
            {
                return;
            }
            var            assembly = selectedNodes[0].PackageEntry;
            SaveFileDialog dlg      = new SaveFileDialog();

            dlg.FileName         = Path.GetFileName(WholeProjectDecompiler.SanitizeFileName(assembly.Name));
            dlg.Filter           = ".NET assemblies|*.dll;*.exe;*.winmd" + Resources.AllFiles;
            dlg.InitialDirectory = Path.GetDirectoryName(bundleNode.LoadedAssembly.FileName);
            if (dlg.ShowDialog() != true)
            {
                return;
            }

            string fileName = dlg.FileName;
            string outputFolderOrFileName = fileName;

            if (selectedNodes.Length > 1)
            {
                outputFolderOrFileName = Path.GetDirectoryName(outputFolderOrFileName);
            }

            Docking.DockWorkspace.Instance.RunWithCancellation(ct => Task <AvalonEditTextOutput> .Factory.StartNew(() => {
                AvalonEditTextOutput output = new AvalonEditTextOutput();
                Stopwatch stopwatch         = Stopwatch.StartNew();
                stopwatch.Stop();

                if (selectedNodes.Length == 1)
                {
                    SaveEntry(output, selectedNodes[0].PackageEntry, outputFolderOrFileName);
                }
                else
                {
                    foreach (var node in selectedNodes)
                    {
                        var fileName = Path.GetFileName(WholeProjectDecompiler.SanitizeFileName(node.PackageEntry.Name));
                        SaveEntry(output, node.PackageEntry, Path.Combine(outputFolderOrFileName, fileName));
                    }
                }
                output.WriteLine(Resources.GenerationCompleteInSeconds, stopwatch.Elapsed.TotalSeconds.ToString("F1"));
                output.WriteLine();
                output.AddButton(null, Resources.OpenExplorer, delegate { Process.Start("explorer", "/select,\"" + fileName + "\""); });
                output.WriteLine();
                return(output);
            }, ct)).Then(output => Docking.DockWorkspace.Instance.ShowText(output)).HandleExceptions();
        }
Ejemplo n.º 3
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);
                    }
                }
            }
            textView.Show(output);
        }
Ejemplo n.º 4
0
 public override bool View(TabPageModel tabPage)
 {
     try
     {
         AvalonEditTextOutput output = new AvalonEditTextOutput();
         BitmapImage          image  = new BitmapImage();
         image.BeginInit();
         image.StreamSource = OpenStream();
         image.EndInit();
         output.AddUIElement(() => new Image {
             Source = image
         });
         output.WriteLine();
         output.AddButton(Images.Save, Resources.Save, delegate {
             Save(null);
         });
         tabPage.ShowTextView(textView => textView.ShowNode(output, this));
         tabPage.SupportsLanguageSwitching = false;
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Ejemplo n.º 5
0
 public override bool View(TabPageModel tabPage)
 {
     try
     {
         AvalonEditTextOutput output = new AvalonEditTextOutput();
         using var data = OpenStream();
         if (data == null)
         {
             return(false);
         }
         IconBitmapDecoder decoder = new IconBitmapDecoder(data, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.OnLoad);
         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, Resources.Save, delegate {
             Save(null);
         });
         tabPage.ShowTextView(textView => textView.ShowNode(output, this));
         tabPage.SupportsLanguageSwitching = false;
         return(true);
     }
     catch (Exception)
     {
         return(false);
     }
 }
Ejemplo n.º 6
0
        static void AddUpdateCheckButton(StackPanel stackPanel, DecompilerTextView textView)
        {
            Button button = ThemeManager.Current.CreateButton();

            button.Content = Resources.CheckUpdates;
            button.Cursor  = Cursors.Arrow;
            stackPanel.Children.Add(button);

            button.Click += async delegate {
                button.Content   = Resources.Checking;
                button.IsEnabled = false;

                try
                {
                    AvailableVersionInfo vInfo = await GetLatestVersionAsync();

                    stackPanel.Children.Clear();
                    ShowAvailableVersion(vInfo, stackPanel);
                }
                catch (Exception ex)
                {
                    AvalonEditTextOutput exceptionOutput = new AvalonEditTextOutput();
                    exceptionOutput.WriteLine(ex.ToString());
                    textView.ShowText(exceptionOutput);
                }
            };
        }
Ejemplo n.º 7
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)).Then(output => MainWindow.Instance.TextView.ShowText(output)).HandleExceptions();
		}
Ejemplo n.º 8
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);
            }
        }
Ejemplo n.º 9
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());
            };
        }
Ejemplo n.º 10
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);
     }
 }
Ejemplo n.º 11
0
        internal static void GeneratePdbForAssembly(LoadedAssembly assembly)
        {
            var file = assembly.GetPEFileOrNull();

            if (!PortablePdbWriter.HasCodeViewDebugDirectoryEntry(file))
            {
                MessageBox.Show(string.Format(Resources.CannotCreatePDBFile, Path.GetFileName(assembly.FileName)));
                return;
            }
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.FileName         = DecompilerTextView.CleanUpName(assembly.ShortName) + ".pdb";
            dlg.Filter           = Resources.PortablePDBPdbAllFiles;
            dlg.InitialDirectory = Path.GetDirectoryName(assembly.FileName);
            if (dlg.ShowDialog() != true)
            {
                return;
            }
            DecompilationOptions options = new DecompilationOptions();
            string fileName = dlg.FileName;

            Docking.DockWorkspace.Instance.RunWithCancellation(ct => Task <AvalonEditTextOutput> .Factory.StartNew(() => {
                AvalonEditTextOutput output = new AvalonEditTextOutput();
                Stopwatch stopwatch         = Stopwatch.StartNew();
                using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write))
                {
                    try
                    {
                        var decompiler = new CSharpDecompiler(file, assembly.GetAssemblyResolver(), options.DecompilerSettings);
                        PortablePdbWriter.WritePdb(file, decompiler, options.DecompilerSettings, stream);
                    }
                    catch (OperationCanceledException)
                    {
                        output.WriteLine();
                        output.WriteLine(Resources.GenerationWasCancelled);
                        throw;
                    }
                }
                stopwatch.Stop();
                output.WriteLine(Resources.GenerationCompleteInSeconds, stopwatch.Elapsed.TotalSeconds.ToString("F1"));
                output.WriteLine();
                output.AddButton(null, Resources.OpenExplorer, delegate { Process.Start("explorer", "/select,\"" + fileName + "\""); });
                output.WriteLine();
                return(output);
            }, ct)).Then(output => Docking.DockWorkspace.Instance.ShowText(output)).HandleExceptions();
        }
Ejemplo n.º 12
0
 void WriteResourceFile(AvalonEditTextOutput output, string name, bool addNewLine = true)
 {
     if (addNewLine)
     {
         output.WriteLine();
     }
     using (var stream = GetType().Assembly.GetManifestResourceStream(name))
         using (var streamReader = new StreamReader(stream, Encoding.UTF8)) {
             for (;;)
             {
                 var line = streamReader.ReadLine();
                 if (line == null)
                 {
                     break;
                 }
                 output.WriteLine(line, TextTokenKind.Text);
             }
         }
 }
Ejemplo n.º 13
0
        internal static void GeneratePdbForAssembly(LoadedAssembly assembly)
        {
            var file = assembly.GetPEFileOrNull();

            if (!PortablePdbWriter.HasCodeViewDebugDirectoryEntry(file))
            {
                MessageBox.Show($"Cannot create PDB file for {Path.GetFileName(assembly.FileName)}, because it does not contain a PE Debug Directory Entry of type 'CodeView'.");
                return;
            }
            SaveFileDialog dlg = new SaveFileDialog();

            dlg.FileName         = DecompilerTextView.CleanUpName(assembly.ShortName) + ".pdb";
            dlg.Filter           = "Portable PDB|*.pdb|All files|*.*";
            dlg.InitialDirectory = Path.GetDirectoryName(assembly.FileName);
            if (dlg.ShowDialog() != true)
            {
                return;
            }
            DecompilationOptions options = new DecompilationOptions();
            string fileName = dlg.FileName;

            MainWindow.Instance.TextView.RunWithCancellation(ct => Task <AvalonEditTextOutput> .Factory.StartNew(() => {
                AvalonEditTextOutput output = new AvalonEditTextOutput();
                Stopwatch stopwatch         = Stopwatch.StartNew();
                using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate, FileAccess.Write)) {
                    try {
                        var decompiler = new CSharpDecompiler(file, assembly.GetAssemblyResolver(), options.DecompilerSettings);
                        PortablePdbWriter.WritePdb(file, decompiler, options.DecompilerSettings, stream);
                    } catch (OperationCanceledException) {
                        output.WriteLine();
                        output.WriteLine("Generation was cancelled.");
                        throw;
                    }
                }
                stopwatch.Stop();
                output.WriteLine("Generation complete in " + stopwatch.Elapsed.TotalSeconds.ToString("F1") + " seconds.");
                output.WriteLine();
                output.AddButton(null, "Open Explorer", delegate { Process.Start("explorer", "/select,\"" + fileName + "\""); });
                output.WriteLine();
                return(output);
            }, ct)).Then(output => MainWindow.Instance.TextView.ShowText(output)).HandleExceptions();
        }
Ejemplo n.º 14
0
        void WriteShortInfo(AvalonEditTextOutput output, string s)
        {
            if (string.IsNullOrEmpty(s))
            {
                return;
            }
            const int MAX_SHORT_LEN = 128;

            if (s.Length > MAX_SHORT_LEN)
            {
                s = s.Substring(0, MAX_SHORT_LEN) + "[...]";
            }
            output.WriteLine(string.Format("\t{0}", s), TextTokenKind.Text);
        }
Ejemplo n.º 15
0
        public void EndAsyncShow(IShowContext ctx, IAsyncShowResult result)
        {
            var decompileContext = (DecompileContext)ctx.UserData;
            var uiCtx            = (ITextEditorUIContext)ctx.UIContext;

            IHighlightingDefinition highlighting;

            if (decompileContext.DecompileNodeContext.HighlightingDefinition != null)
            {
                highlighting = decompileContext.DecompileNodeContext.HighlightingDefinition;
            }
            else if (decompileContext.DecompileNodeContext.HighlightingExtension != null)
            {
                highlighting = HighlightingManager.Instance.GetDefinitionByExtension(decompileContext.DecompileNodeContext.HighlightingExtension);
            }
            else
            {
                highlighting = decompileContext.DecompileNodeContext.Language.GetHighlightingDefinition();
            }

            AvalonEditTextOutput output;

            if (result.IsCanceled)
            {
                output = new AvalonEditTextOutput();
                output.Write(dnSpy_Resources.DecompilationCanceled, TextTokenKind.Error);
            }
            else if (result.Exception != null)
            {
                output = new AvalonEditTextOutput();
                output.Write(dnSpy_Resources.DecompilationException, TextTokenKind.Error);
                output.WriteLine();
                output.Write(result.Exception.ToString(), TextTokenKind.Text);
            }
            else
            {
                output = decompileContext.CachedOutput;
                if (output == null)
                {
                    output = (AvalonEditTextOutput)decompileContext.DecompileNodeContext.Output;
                    decompileFileTabContentFactory.DecompilationCache.Cache(decompileContext.DecompileNodeContext.Language, nodes, output, highlighting);
                }
            }

            if (result.CanShowOutput)
            {
                uiCtx.SetOutput(output, highlighting);
            }
        }
Ejemplo n.º 16
0
        public override bool View(TabPageModel tabPage)
        {
            try
            {
                AvalonEditTextOutput output = new AvalonEditTextOutput();
                BitmapImage          image  = new BitmapImage();
                byte[] curData;
                using (var data = OpenStream())
                {
                    if (data == null)
                    {
                        return(false);
                    }
                    //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 (s == null)
                    {
                        // data was stored in another stream type (e.g. PinnedBufferedMemoryStream)
                        s = new MemoryStream();
                        data.CopyTo(s);
                    }
                    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(Images.Save, Resources.Save, delegate {
                    Save(null);
                });
                tabPage.ShowTextView(textView => textView.ShowNode(output, this));
                tabPage.SupportsLanguageSwitching = false;
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
Ejemplo n.º 17
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.ShowText(output);
     }
 }
Ejemplo n.º 18
0
 void Write(AvalonEditTextOutput output)
 {
     output.WriteLine($"deAtomizer {appWindow.AssemblyInformationalVersion}", TextTokenKind.Text);
     output.WriteLine();
     output.WriteLine(dnSpy_Resources.AboutScreen_LicenseInfo, TextTokenKind.Text);
     output.WriteLine();
     output.WriteLine(dnSpy_Resources.AboutScreen_LoadedFiles, TextTokenKind.Text);
     foreach (var info in GetInfos())
     {
         output.WriteLine();
         WriteShortInfo(output, info.NameAndVersion);
         WriteShortInfo(output, info.Copyright);
         WriteShortInfo(output, info.ShortDescription);
     }
     output.WriteLine();
     WriteResourceFile(output, "dnSpy.CREDITS.txt");
 }
Ejemplo n.º 19
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);
     }
 }
Ejemplo n.º 20
0
 void Write(AvalonEditTextOutput output)
 {
     output.WriteLine(string.Format("dnSpy {0}", appWindow.AssemblyInformationalVersion), TextTokenKind.Text);
     output.WriteLine();
     output.WriteLine(dnSpy_Resources.AboutScreen_LicenseInfo, TextTokenKind.Text);
     output.WriteLine();
     output.WriteLine(dnSpy_Resources.AboutScreen_LoadedFiles, TextTokenKind.Text);
     foreach (var info in GetInfos())
     {
         output.WriteLine();
         WriteShortInfo(output, info.Name);
         WriteShortInfo(output, info.Copyright);
         WriteShortInfo(output, info.ShortDescription);
     }
 }
Ejemplo n.º 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;
     }
 }
Ejemplo n.º 22
0
        public override bool View(TabPageModel tabPage)
        {
            AvalonEditTextOutput    output       = new AvalonEditTextOutput();
            IHighlightingDefinition highlighting = null;

            tabPage.ShowTextView(textView => textView.RunWithCancellation(
                                     token => Task.Factory.StartNew(
                                         () => {
                try
                {
                    // cache read XAML because stream will be closed after first read
                    if (xml == null)
                    {
                        using var data = OpenStream();
                        if (data == null)
                        {
                            output.Write("ILSpy: Failed opening resource stream.");
                            output.WriteLine();
                            return(output);
                        }
                        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());
            tabPage.SupportsLanguageSwitching = false;
            return(true);
        }
Ejemplo n.º 23
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);
            }
        }
Ejemplo n.º 24
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);
     }
 }
Ejemplo n.º 25
0
        public static void Display(DecompilerTextView textView)
        {
            AvalonEditTextOutput output = new AvalonEditTextOutput()
            {
                Title = Resources.About, EnableHyperlinks = true
            };

            output.WriteLine(Resources.ILSpyVersion + RevisionClass.FullVersion);
            if (WindowsVersionHelper.HasPackageIdentity)
            {
                output.WriteLine($"Package Name: {WindowsVersionHelper.GetPackageFamilyName()}");
            }
            else                // if we're running in an MSIX, updates work differently
            {
                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        = Resources.AutomaticallyCheckUpdatesEveryWeek;
                    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.ExportProvider.GetExportedValues <IAboutPageAddition>())
            {
                plugin.Write(output);
            }
            output.WriteLine();
            output.Address = new Uri("resource://AboutPage");
            using (Stream s = typeof(AboutPage).Assembly.GetManifestResourceStream(typeof(AboutPage), Resources.ILSpyAboutPageTxt)) {
                using (StreamReader r = new StreamReader(s)) {
                    string line;
                    while ((line = r.ReadLine()) != null)
                    {
                        output.WriteLine(line);
                    }
                }
            }
            output.AddVisualLineElementGenerator(new MyLinkElementGenerator("MIT License", "resource:license.txt"));
            output.AddVisualLineElementGenerator(new MyLinkElementGenerator("third-party notices", "resource:third-party-notices.txt"));
            textView.ShowText(output);
        }
Ejemplo n.º 26
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(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 }
                    });
                });
            }
            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(AboutPage), "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");

            //reset icon bar
            textView.manager.Bookmarks.Clear();
        }
Ejemplo n.º 27
0
 public void WriteNewLine()
 {
     output.WriteLine();
     needsNewLine = false;
 }
Ejemplo n.º 28
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;
     }
 }
Ejemplo n.º 29
0
        async Task <AvalonEditTextOutput> CreateSolution(IEnumerable <LoadedAssembly> assemblies, Language language, CancellationToken ct)
        {
            var result = new AvalonEditTextOutput();

            var duplicates = new HashSet <string>();

            if (assemblies.Any(asm => !duplicates.Add(asm.ShortName)))
            {
                result.WriteLine("Duplicate assembly names selected, cannot generate a solution.");
                return(result);
            }

            Stopwatch stopwatch = Stopwatch.StartNew();

            try
            {
                // Explicitly create an enumerable partitioner here to avoid Parallel.ForEach's special cases for lists,
                // as those seem to use static partitioning which is inefficient if assemblies take differently
                // long to decompile.
                await Task.Run(() => Parallel.ForEach(Partitioner.Create(assemblies),
                                                      new ParallelOptions {
                    MaxDegreeOfParallelism = Environment.ProcessorCount, CancellationToken = ct
                },
                                                      n => WriteProject(n, language, solutionDirectory, ct)))
                .ConfigureAwait(false);

                if (projects.Count == 0)
                {
                    result.WriteLine();
                    result.WriteLine("Solution could not be created, because none of the selected assemblies could be decompiled into a project.");
                }
                else
                {
                    await Task.Run(() => SolutionCreator.WriteSolutionFile(solutionFilePath, projects))
                    .ConfigureAwait(false);
                }
            }
            catch (AggregateException ae)
            {
                if (ae.Flatten().InnerExceptions.All(e => e is OperationCanceledException))
                {
                    result.WriteLine();
                    result.WriteLine("Generation was cancelled.");
                    return(result);
                }

                result.WriteLine();
                result.WriteLine("Failed to generate the Visual Studio Solution. Errors:");
                ae.Handle(e => {
                    result.WriteLine(e.Message);
                    return(true);
                });

                return(result);
            }

            foreach (var item in statusOutput)
            {
                result.WriteLine(item);
            }

            if (statusOutput.Count == 0)
            {
                result.WriteLine("Successfully decompiled the following assemblies into Visual Studio projects:");
                foreach (var item in assemblies.Select(n => n.Text.ToString()))
                {
                    result.WriteLine(item);
                }

                result.WriteLine();

                if (assemblies.Count() == projects.Count)
                {
                    result.WriteLine("Created the Visual Studio Solution file.");
                }

                result.WriteLine();
                result.WriteLine("Elapsed time: " + stopwatch.Elapsed.TotalSeconds.ToString("F1") + " seconds.");
                result.WriteLine();
                result.AddButton(null, "Open Explorer", delegate { Process.Start("explorer", "/select,\"" + solutionFilePath + "\""); });
            }

            return(result);
        }
Ejemplo n.º 30
0
        async Task <AvalonEditTextOutput> CreateSolution(IEnumerable <LoadedAssembly> assemblies, Language language, CancellationToken ct)
        {
            var result = new AvalonEditTextOutput();

            var duplicates = new HashSet <string>();

            if (assemblies.Any(asm => !duplicates.Add(asm.ShortName)))
            {
                result.WriteLine("Duplicate assembly names selected, cannot generate a solution.");
                return(result);
            }

            Stopwatch stopwatch = Stopwatch.StartNew();

            try {
                await Task.Run(() => Parallel.ForEach(assemblies, n => WriteProject(n, language, solutionDirectory, ct)))
                .ConfigureAwait(false);

                await Task.Run(() => SolutionCreator.WriteSolutionFile(solutionFilePath, projects))
                .ConfigureAwait(false);
            } catch (AggregateException ae) {
                if (ae.Flatten().InnerExceptions.All(e => e is OperationCanceledException))
                {
                    result.WriteLine();
                    result.WriteLine("Generation was cancelled.");
                    return(result);
                }

                result.WriteLine();
                result.WriteLine("Failed to generate the Visual Studio Solution. Errors:");
                ae.Handle(e => {
                    result.WriteLine(e.Message);
                    return(true);
                });

                return(result);
            }

            foreach (var item in statusOutput)
            {
                result.WriteLine(item);
            }

            if (statusOutput.Count == 0)
            {
                result.WriteLine("Successfully decompiled the following assemblies into Visual Studio projects:");
                foreach (var item in assemblies.Select(n => n.Text.ToString()))
                {
                    result.WriteLine(item);
                }

                result.WriteLine();

                if (assemblies.Count() == projects.Count)
                {
                    result.WriteLine("Created the Visual Studio Solution file.");
                }

                result.WriteLine();
                result.WriteLine("Elapsed time: " + stopwatch.Elapsed.TotalSeconds.ToString("F1") + " seconds.");
                result.WriteLine();
                result.AddButton(null, "Open Explorer", delegate { Process.Start("explorer", "/select,\"" + solutionFilePath + "\""); });
            }

            return(result);
        }
Ejemplo n.º 31
0
        void Write(AvalonEditTextOutput output)
        {
            output.WriteLine(string.Format("dnSpy {0}", appWindow.AssemblyInformationalVersion), TextTokenKind.Text);

            //TODO: Add more stuff...
        }