-
Notifications
You must be signed in to change notification settings - Fork 12
/
BackgroundParsingTask.cs
97 lines (85 loc) · 3.35 KB
/
BackgroundParsingTask.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace SassyStudio.Compiler
{
[Export(typeof(IBackgroundParsingTask))]
class BackgroundParsingTask : IBackgroundParsingTask
{
readonly IDocumentParserFactory ParserFactory;
readonly CancellationToken ShutdownToken;
readonly BlockingCollection<BackgroundParseRequest> Requests = new BlockingCollection<BackgroundParseRequest>();
[ImportingConstructor]
public BackgroundParsingTask(IDocumentParserFactory parserFactory, IDocumentManager documentManager)
{
ParserFactory = parserFactory;
ShutdownToken = SassyStudioPackage.Instance.ShutdownToken;
documentManager.DocumentAdded += OnDocumentAdded;
}
public void Start()
{
Task.Factory.StartNew(() => ProcessRequests(), ShutdownToken, TaskCreationOptions.DenyChildAttach | TaskCreationOptions.LongRunning, TaskScheduler.Default);
}
void OnDocumentAdded(object sender, DocumentAddedEventArgs e)
{
Requests.Add(new BackgroundParseRequest(e.Document));
}
void ProcessRequests()
{
while (!ShutdownToken.IsCancellationRequested)
{
BackgroundParseRequest request;
if (Requests.TryTake(out request, -1, ShutdownToken))
{
try
{
var source = request.Document.Source;
source.Refresh();
if (source.Exists)
{
ISassStylesheet stylesheet = null;
var textManager = new FileTextManager(source);
using (var scope = textManager.Open())
{
var parser = ParserFactory.Create();
stylesheet = parser.Parse(new FileParsingRequest(scope.Text, request.Document));
}
if (stylesheet != null)
request.Document.Update(stylesheet);
}
}
catch (Exception ex)
{
Logger.Log(ex, "Failed to process background document parse request.");
}
}
}
}
class FileParsingRequest : IParsingRequest
{
public FileParsingRequest(ITextProvider provider, ISassDocument document)
{
Text = provider;
Document = document;
}
public ISassDocument Document { get; set; }
public ITextProvider Text { get; private set; }
public DateTime RequestedOn { get; private set; }
public bool IsCancelled { get { return false; } }
}
class BackgroundParseRequest
{
private ISassDocument _Document;
public BackgroundParseRequest(ISassDocument document)
{
_Document = document;
}
public ISassDocument Document { get { return _Document; } }
}
}
}