Skip to content

Commit

Permalink
Add JumpToReferenceAsync() overload to allow detecting when the decom…
Browse files Browse the repository at this point in the history
…pilation after the jump has finished.
  • Loading branch information
dgrunwald committed Jun 7, 2014
1 parent 0894e4c commit 9084ce2
Show file tree
Hide file tree
Showing 9 changed files with 312 additions and 65 deletions.
8 changes: 4 additions & 4 deletions ILSpy.BamlDecompiler/BamlResourceEntryNode.cs
Original file line number Diff line number Diff line change
Expand Up @@ -26,22 +26,22 @@ public BamlResourceEntryNode(string key, Stream data) : base(key, data)

public override bool View(DecompilerTextView textView)
{
AvalonEditTextOutput output = new AvalonEditTextOutput();
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),
t => textView.ShowNode(t.Result, this, highlighting)
);
}, token))
.Then(output => textView.ShowNode(output, this, highlighting))
.HandleExceptions();
return true;
}

Expand Down
8 changes: 8 additions & 0 deletions ILSpy/App.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Navigation;
Expand Down Expand Up @@ -92,6 +93,7 @@ public App()
AppDomain.CurrentDomain.UnhandledException += ShowErrorBox;
Dispatcher.CurrentDispatcher.UnhandledException += Dispatcher_UnhandledException;
}
TaskScheduler.UnobservedTaskException += DotNet40_UnobservedTaskException;

EventManager.RegisterClassHandler(typeof(Window),
Hyperlink.RequestNavigateEvent,
Expand All @@ -111,6 +113,12 @@ string FullyQualifyPath(string argument)
return argument;
}
}

void DotNet40_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
{
// On .NET 4.0, an unobserved exception in a task terminates the process unless we mark it as observed
e.SetObserved();
}

#region Exception Handling
static void Dispatcher_UnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
Expand Down
2 changes: 1 addition & 1 deletion ILSpy/Commands/DecompileAllCommand.cs
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ public override void Execute(object parameter)
}
});
return output;
}, ct), task => MainWindow.Instance.TextView.ShowText(task.Result));
}, ct)).Then(output => MainWindow.Instance.TextView.ShowText(output)).HandleExceptions();
}
}
}
Expand Down
1 change: 1 addition & 0 deletions ILSpy/ILSpy.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -177,6 +177,7 @@
<SubType>Code</SubType>
</Compile>
<Compile Include="Commands\SimpleCommand.cs" />
<Compile Include="TaskHelper.cs" />
<Compile Include="TextView\FoldingCommands.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzeContextMenuEntry.cs" />
<Compile Include="TreeNodes\Analyzer\AnalyzedAssemblyTreeNode.cs" />
Expand Down
17 changes: 16 additions & 1 deletion ILSpy/MainWindow.xaml.cs
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,19 @@ public ILSpyTreeNode FindTreeNode(object reference)

public void JumpToReference(object reference)
{
JumpToReferenceAsync(reference).HandleExceptions();
}

/// <summary>
/// Jumps to the specified reference.
/// </summary>
/// <returns>
/// Returns a task that will signal completion when the decompilation of the jump target has finished.
/// The task will be marked as canceled if the decompilation is canceled.
/// </returns>
public Task JumpToReferenceAsync(object reference)
{
decompilationTask = TaskHelper.CompletedTask;
ILSpyTreeNode treeNode = FindTreeNode(reference);
if (treeNode != null) {
SelectNode(treeNode);
Expand All @@ -569,6 +582,7 @@ public void JumpToReference(object reference)

}
}
return decompilationTask;
}
#endregion

Expand Down Expand Up @@ -627,6 +641,7 @@ void TreeView_SelectionChanged(object sender, SelectionChangedEventArgs e)
DecompileSelectedNodes();
}

Task decompilationTask;
bool ignoreDecompilationRequests;

void DecompileSelectedNodes(DecompilerTextViewState state = null, bool recordHistory = true)
Expand All @@ -646,7 +661,7 @@ void DecompileSelectedNodes(DecompilerTextViewState state = null, bool recordHis
if (node != null && node.View(decompilerTextView))
return;
}
decompilerTextView.Decompile(this.CurrentLanguage, this.SelectedNodes, new DecompilationOptions() { TextViewState = state });
decompilationTask = decompilerTextView.DecompileAsync(this.CurrentLanguage, this.SelectedNodes, new DecompilationOptions() { TextViewState = state });
}

void SaveCommandExecuted(object sender, ExecutedRoutedEventArgs e)
Expand Down
203 changes: 203 additions & 0 deletions ILSpy/TaskHelper.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,203 @@
// Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.

using System;
using System.Threading;
using System.Threading.Tasks;
using ICSharpCode.ILSpy.TextView;

namespace ICSharpCode.ILSpy
{
public static class TaskHelper
{
public static readonly Task CompletedTask = FromResult<object>(null);

public static Task<T> FromResult<T>(T result)
{
TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
tcs.SetResult(result);
return tcs.Task;
}

public static Task<T> FromException<T>(Exception ex)
{
var tcs = new TaskCompletionSource<T>();
tcs.SetException(ex);
return tcs.Task;
}

public static Task<T> FromCancellation<T>()
{
var tcs = new TaskCompletionSource<T>();
tcs.SetCanceled();
return tcs.Task;
}

/// <summary>
/// Sets the result of the TaskCompletionSource based on the result of the finished task.
/// </summary>
public static void SetFromTask<T>(this TaskCompletionSource<T> tcs, Task<T> task)
{
switch (task.Status) {
case TaskStatus.RanToCompletion:
tcs.SetResult(task.Result);
break;
case TaskStatus.Canceled:
tcs.SetCanceled();
break;
case TaskStatus.Faulted:
tcs.SetException(task.Exception.InnerExceptions);
break;
default:
throw new InvalidOperationException("The input task must have already finished");
}
}

/// <summary>
/// Sets the result of the TaskCompletionSource based on the result of the finished task.
/// </summary>
public static void SetFromTask(this TaskCompletionSource<object> tcs, Task task)
{
switch (task.Status) {
case TaskStatus.RanToCompletion:
tcs.SetResult(null);
break;
case TaskStatus.Canceled:
tcs.SetCanceled();
break;
case TaskStatus.Faulted:
tcs.SetException(task.Exception.InnerExceptions);
break;
default:
throw new InvalidOperationException("The input task must have already finished");
}
}

public static Task Then<T>(this Task<T> task, Action<T> action)
{
if (action == null)
throw new ArgumentNullException("action");
return task.ContinueWith(t => action(t.Result), CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext());
}

public static Task<U> Then<T, U>(this Task<T> task, Func<T, U> func)
{
if (func == null)
throw new ArgumentNullException("func");
return task.ContinueWith(t => func(t.Result), CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext());
}

public static Task Then<T>(this Task<T> task, Func<T, Task> asyncFunc)
{
if (asyncFunc == null)
throw new ArgumentNullException("asyncFunc");
return task.ContinueWith(t => asyncFunc(t.Result), CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext()).Unwrap();
}

public static Task<U> Then<T, U>(this Task<T> task, Func<T, Task<U>> asyncFunc)
{
if (asyncFunc == null)
throw new ArgumentNullException("asyncFunc");
return task.ContinueWith(t => asyncFunc(t.Result), CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext()).Unwrap();
}

public static Task Then(this Task task, Action action)
{
if (action == null)
throw new ArgumentNullException("action");
return task.ContinueWith(t => {
t.Wait();
action();
}, CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext());
}

public static Task<U> Then<U>(this Task task, Func<U> func)
{
if (func == null)
throw new ArgumentNullException("func");
return task.ContinueWith(t => {
t.Wait();
return func();
}, CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext());
}

public static Task Then(this Task task, Func<Task> asyncAction)
{
if (asyncAction == null)
throw new ArgumentNullException("asyncAction");
return task.ContinueWith(t => {
t.Wait();
return asyncAction();
}, CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext()).Unwrap();
}

public static Task<U> Then<U>(this Task task, Func<Task<U>> asyncFunc)
{
if (asyncFunc == null)
throw new ArgumentNullException("asyncFunc");
return task.ContinueWith(t => {
t.Wait();
return asyncFunc();
}, CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext()).Unwrap();
}

/// <summary>
/// If the input task fails, calls the action to handle the error.
/// </summary>
/// <returns>
/// Returns a task that finishes successfully when error handling has completed.
/// If the input task ran successfully, the returned task completes successfully.
/// If the input task was cancelled, the returned task is cancelled as well.
/// </returns>
public static Task Catch<TException>(this Task task, Action<TException> action) where TException : Exception
{
if (action == null)
throw new ArgumentNullException("action");
return task.ContinueWith(t => {
if (t.IsFaulted) {
Exception ex = t.Exception;
while (ex is AggregateException)
ex = ex.InnerException;
if (ex is TException)
action((TException)ex);
else
throw t.Exception;
}
}, CancellationToken.None, TaskContinuationOptions.NotOnCanceled, TaskScheduler.FromCurrentSynchronizationContext());
}

/// <summary>
/// Ignore exceptions thrown by the task.
/// </summary>
public static void IgnoreExceptions(this Task task)
{
}

/// <summary>
/// Handle exceptions by displaying the error message in the text view.
/// </summary>
public static void HandleExceptions(this Task task)
{
task.Catch<Exception>(exception => MainWindow.Instance.Dispatcher.BeginInvoke(new Action(delegate {
AvalonEditTextOutput output = new AvalonEditTextOutput();
output.Write(exception.ToString());
MainWindow.Instance.TextView.ShowText(output);
}))).IgnoreExceptions();
}
}
}
Loading

0 comments on commit 9084ce2

Please sign in to comment.