-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy pathScriptEditorPage.xaml.cs
More file actions
215 lines (185 loc) · 8.61 KB
/
ScriptEditorPage.xaml.cs
File metadata and controls
215 lines (185 loc) · 8.61 KB
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
using System;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.UI;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Microsoft.UI.Xaml.Media;
using FluentTaskScheduler.ViewModels;
using FluentTaskScheduler.Services;
namespace FluentTaskScheduler
{
public sealed partial class ScriptEditorPage : Page
{
private Process? _runningProcess;
private readonly DispatcherTimer _highlightTimer;
private bool _isHighlighting = false;
public ScriptEditorPage()
{
this.InitializeComponent();
_highlightTimer = new DispatcherTimer { Interval = TimeSpan.FromMilliseconds(500) };
_highlightTimer.Tick += (s, e) => { _highlightTimer.Stop(); HighlightCode(); };
}
private void Page_Loaded(object sender, RoutedEventArgs e)
{
CodeEditor.Focus(FocusState.Programmatic);
}
private async void RunButton_Click(object sender, RoutedEventArgs e)
{
string code;
CodeEditor.Document.GetText(Microsoft.UI.Text.TextGetOptions.None, out code);
if (string.IsNullOrWhiteSpace(code)) return;
await RunScript(code);
}
private void StopButton_Click(object sender, RoutedEventArgs e)
{
try
{
if (_runningProcess != null && !_runningProcess.HasExited)
{
_runningProcess.Kill(true);
AppendOutput("\n" + LocalizationService.GetString("ScriptEditor.Status.Stopped", "[Stopped by user]") + "\n", Colors.Red);
}
}
catch { }
}
private void ClearButton_Click(object sender, RoutedEventArgs e)
{
OutputConsole.Text = "";
}
private async void SaveButton_Click(object sender, RoutedEventArgs e)
{
string code;
CodeEditor.Document.GetText(Microsoft.UI.Text.TextGetOptions.None, out code);
if (string.IsNullOrWhiteSpace(code)) return;
var dialog = new ContentDialog
{
Title = LocalizationService.GetString("ScriptEditor.SaveDialog.Title", "Save Script to Library"),
PrimaryButtonText = LocalizationService.GetString("Dialog.Common.Save", "Save"),
CloseButtonText = LocalizationService.GetString("Dialog.Common.Cancel", "Cancel"),
DefaultButton = ContentDialogButton.Primary,
XamlRoot = this.XamlRoot
};
var stack = new StackPanel { Spacing = 12 };
var nameBox = new TextBox { Header = LocalizationService.GetString("ScriptEditor.SaveDialog.NameHeader", "Template Name"), PlaceholderText = "e.g. My Custom Cleanup" };
var descBox = new TextBox { Header = LocalizationService.GetString("ScriptEditor.SaveDialog.DescHeader", "Description"), PlaceholderText = "What does this script do?" };
stack.Children.Add(nameBox);
stack.Children.Add(descBox);
dialog.Content = stack;
if (await dialog.ShowAsync() == ContentDialogResult.Primary && !string.IsNullOrWhiteSpace(nameBox.Text))
{
// Save script to a temporary file in local app data
string scriptsDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "FluentTaskScheduler", "Scripts");
Directory.CreateDirectory(scriptsDir);
string fileName = $"{Guid.NewGuid()}.ps1";
string fullPath = Path.Combine(scriptsDir, fileName);
File.WriteAllText(fullPath, code);
var viewModel = new ScriptLibraryViewModel();
viewModel.AddUserTemplate(new ScriptTemplateModel
{
Name = nameBox.Text,
Description = descBox.Text,
Command = "powershell.exe",
Arguments = $"-ExecutionPolicy Bypass -File \"{fullPath}\"",
IsUserTemplate = true
});
AppendOutput("\n" + string.Format(LocalizationService.GetString("ScriptEditor.Status.Saved", "[Saved to Library as '{0}']"), nameBox.Text) + "\n", Colors.Green);
}
}
private async Task RunScript(string code)
{
RunButton.IsEnabled = false;
StopButton.IsEnabled = true;
OutputConsole.Text = LocalizationService.GetString("ScriptEditor.Status.Starting", "[Starting PowerShell...]") + "\n";
string tempFile = Path.Combine(Path.GetTempPath(), $"ft_temp_{Guid.NewGuid()}.ps1");
File.WriteAllText(tempFile, code);
try
{
_runningProcess = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = "powershell.exe",
Arguments = $"-ExecutionPolicy Bypass -File \"{tempFile}\"",
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true,
RedirectStandardError = true,
StandardOutputEncoding = Encoding.UTF8
},
EnableRaisingEvents = true
};
_runningProcess.OutputDataReceived += (s, e) => { if (e.Data != null) AppendOutput(e.Data + "\n", Colors.LightGray); };
_runningProcess.ErrorDataReceived += (s, e) => { if (e.Data != null) AppendOutput(e.Data + "\n", Colors.Red); };
_runningProcess.Start();
_runningProcess.BeginOutputReadLine();
_runningProcess.BeginErrorReadLine();
await _runningProcess.WaitForExitAsync();
}
catch (Exception ex)
{
AppendOutput($"Error: {ex.Message}\n", Colors.Red);
}
finally
{
if (File.Exists(tempFile)) File.Delete(tempFile);
RunButton.IsEnabled = true;
StopButton.IsEnabled = false;
AppendOutput("\n" + LocalizationService.GetString("ScriptEditor.Status.Exited", "[Process Exited]") + "\n", Colors.Gray);
}
}
private void AppendOutput(string text, Windows.UI.Color color)
{
DispatcherQueue.TryEnqueue(() =>
{
// In a real app we'd use a RichTextBlock or colored spans
// For now, just plain text to keep it simple but functional
OutputConsole.Text += text;
});
}
private void CodeEditor_TextChanged(object sender, RoutedEventArgs e)
{
if (_isHighlighting) return;
_highlightTimer.Stop();
_highlightTimer.Start();
}
private void HighlightCode()
{
_isHighlighting = true;
// Basic PowerShell highlighting
string[] keywords = { "if", "else", "elseif", "foreach", "while", "function", "return", "try", "catch", "finally", "throw", "break", "continue", "param", "in" };
// We need to save the selection to restore it
var selection = CodeEditor.Document.Selection;
int start = selection.StartPosition;
int end = selection.EndPosition;
// Clear formatting first
var allRange = CodeEditor.Document.GetRange(0, Microsoft.UI.Text.TextConstants.MaxUnitCount);
allRange.CharacterFormat.ForegroundColor = Colors.White;
string text;
allRange.GetText(Microsoft.UI.Text.TextGetOptions.None, out text);
// This is a VERY naive highlighter for demonstration
foreach (var word in keywords)
{
HighlightWord(word, Colors.CornflowerBlue);
}
// Restore selection
CodeEditor.Document.Selection.SetRange(start, end);
_isHighlighting = false;
}
private void HighlightWord(string word, Windows.UI.Color color)
{
int start = 0;
while (true)
{
var range = CodeEditor.Document.GetRange(start, Microsoft.UI.Text.TextConstants.MaxUnitCount);
int found = range.FindText(word, Microsoft.UI.Text.TextConstants.MaxUnitCount, Microsoft.UI.Text.FindOptions.None);
if (found <= 0) break;
range.CharacterFormat.ForegroundColor = color;
start = range.EndPosition;
}
}
}
}