-
-
Notifications
You must be signed in to change notification settings - Fork 81
Expand file tree
/
Copy pathSampleCodePresenter.xaml.cs
More file actions
311 lines (279 loc) · 12.3 KB
/
SampleCodePresenter.xaml.cs
File metadata and controls
311 lines (279 loc) · 12.3 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
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
using ColorCodeStandard;
using ICSharpCode.AvalonEdit;
using ICSharpCode.AvalonEdit.Editing;
using ICSharpCode.AvalonEdit.Highlighting;
using iNKORE.UI.WPF.Modern.Gallery.Helpers;
using SamplesCommon;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MessageBox = iNKORE.UI.WPF.Modern.Controls.MessageBox;
namespace iNKORE.UI.WPF.Modern.Gallery.Controls
{
/// <summary>
/// SampleCodePresenter.xaml 的交互逻辑
/// </summary>
public partial class SampleCodePresenter : UserControl
{
public static readonly DependencyProperty CodeProperty = DependencyProperty.Register("Code", typeof(string), typeof(SampleCodePresenter), new PropertyMetadata(string.Empty, OnCodeSourceFilePropertyChanged));
public string Code
{
get { return (string)GetValue(CodeProperty); }
set { SetValue(CodeProperty, value); }
}
public static readonly DependencyProperty IsCSharpSampleProperty = DependencyProperty.Register("IsCSharpSample", typeof(bool), typeof(SampleCodePresenter), new PropertyMetadata(false, OnCodeSourceFilePropertyChanged));
public bool IsCSharpSample
{
get { return (bool)GetValue(IsCSharpSampleProperty); }
set { SetValue(IsCSharpSampleProperty, value); }
}
public static readonly DependencyProperty SubstitutionsProperty = DependencyProperty.Register("Substitutions", typeof(ObservableCollection<ControlExampleSubstitution>), typeof(SampleCodePresenter), new PropertyMetadata(null, OnSubstitutionsPropertyChanged));
public ObservableCollection<ControlExampleSubstitution> Substitutions
{
get => (ObservableCollection<ControlExampleSubstitution>)GetValue(SubstitutionsProperty);
set
{
if (value == null)
{
ClearValue(SubstitutionsProperty);
}
else
{
SetValue(SubstitutionsProperty, value);
}
}
}
public bool IsEmpty => string.IsNullOrEmpty(Code);
private static Regex SubstitutionPattern = new Regex(@"\$\(([^\)]+)\)");
public SampleCodePresenter()
{
InitializeComponent();
CodePresenter.TextArea.SelectionBorder = new Pen(Brushes.Transparent, 0);
CodePresenter.TextArea.SelectionCornerRadius = 0;
CodePresenter.TextArea.SetResourceReference(TextArea.SelectionBrushProperty, ThemeKeys.TextControlSelectionHighlightColorKey);
// Ensure caret never shows (keep selection & copy)
HideCaretPermanently();
CodePresenter.TextArea.GotFocus += (s,e)=> HideCaretPermanently();
CodePresenter.TextArea.TextView.VisualLinesChanged += (s,e)=> HideCaretPermanently();
}
private void HideCaretPermanently()
{
// Make sure the editor can still be clicked for selection but caret invisible.
var caret = CodePresenter.TextArea.Caret;
caret.CaretBrush = Brushes.Transparent;
// keep focus off the editor so IME/caret logic does not repaint a visible caret
if (CodePresenter.IsFocused)
{
// Move focus to parent container (still allows mouse selection highlight within AvalonEdit)
var parent = (DependencyObject)CodePresenter.Parent;
while (parent != null && parent is not Control)
{
parent = LogicalTreeHelper.GetParent(parent);
}
(parent as Control)?.Focusable.Equals(true);
}
}
private static void OnSubstitutionsPropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
{
if (target is SampleCodePresenter presenter)
{
presenter.RegisterSubstitutions();
}
}
private static void OnCodeSourceFilePropertyChanged(DependencyObject target, DependencyPropertyChangedEventArgs args)
{
if (target is SampleCodePresenter presenter)
{
presenter.ReevaluateVisibility();
}
}
private void ReevaluateVisibility()
{
if (string.IsNullOrEmpty(Code))
{
Visibility = Visibility.Collapsed;
}
else
{
Visibility = Visibility.Visible;
GenerateSyntaxHighlightedContent();
SampleHeader.Text = IsCSharpSample ? "C#" : "XAML";
}
}
private void RegisterSubstitutions()
{
foreach (var substitution in Substitutions)
{
substitution.ValueChanged += OnValueChanged;
}
}
private void SampleCodePresenter_Loaded(object sender, RoutedEventArgs e)
{
ReevaluateVisibility();
SampleHeader.Text = IsCSharpSample ? "C#" : "XAML";
FixAvalonEditScrolling();
try
{
if (CodePresenter?.ContextMenu != null)
{
// Local function to build centered tooltip similar to library TextContextMenu style.
ToolTip BuildCenteredMouseToolTip(string text)
{
var tt = new ToolTip
{
Content = text,
Placement = System.Windows.Controls.Primitives.PlacementMode.Mouse
};
tt.Opened += (s2, e2) =>
{
if (s2 is ToolTip t)
{
t.HorizontalOffset = 0;
t.VerticalOffset = 0;
void ApplyOffsets()
{
const double gap = 32;
t.HorizontalOffset = -t.ActualWidth / 2.0;
t.VerticalOffset = -(t.ActualHeight + gap);
}
if (t.ActualWidth <= 0 || t.ActualHeight <= 0)
{
t.Dispatcher.BeginInvoke((Action)(() =>
{
ApplyOffsets();
}));
}
else
{
ApplyOffsets();
}
}
};
return tt;
}
// Apply tooltip/header customization.
foreach (var item in CodePresenter.ContextMenu.Items.OfType<MenuItem>())
{
if (item.Command == ApplicationCommands.Copy)
{
item.Header = "Copy";
item.ToolTip = BuildCenteredMouseToolTip("Copy the selected content to the clipboard");
ToolTipService.SetInitialShowDelay(item, 700);
}
else if (item.Command == ApplicationCommands.SelectAll)
{
item.Header = "Select All";
item.ToolTip = BuildCenteredMouseToolTip("Select all content");
ToolTipService.SetInitialShowDelay(item, 700);
}
}
// Adjust context menu to only show 'Copy' if there is a selection
CodePresenter.ContextMenu.Opened += (s, args) =>
{
var hasSelection = CodePresenter?.SelectionLength > 0;
foreach (var mi in CodePresenter.ContextMenu.Items.OfType<MenuItem>())
{
if (mi.Command == ApplicationCommands.Copy)
{
mi.Visibility = hasSelection == true ? Visibility.Visible : Visibility.Collapsed;
}
else if (mi.Command == ApplicationCommands.SelectAll)
{
mi.Visibility = Visibility.Visible;
}
}
};
}
}
catch
{
// Exception can happen if the localization resources are not loaded, ignore it.
}
}
private void CodePresenter_Loaded(object sender, RoutedEventArgs e)
{
GenerateSyntaxHighlightedContent();
}
private void SampleCodePresenter_ActualThemeChanged(object sender, RoutedEventArgs e)
{
// If the theme has changed after the user has already opened the app (ie. via settings), then the new locally set theme will overwrite the colors that are set during Loaded.
// Therefore we need to re-format the REB to use the correct colors.
GenerateSyntaxHighlightedContent();
}
private void OnValueChanged(ControlExampleSubstitution sender, object e)
{
GenerateSyntaxHighlightedContent();
}
private void GenerateSyntaxHighlightedContent()
{
FormatAndRenderSampleFromString(Code, CodePresenter, IsCSharpSample ? Languages.CSharp : Languages.Xml);
}
private void FormatAndRenderSampleFromString(string sampleString, TextEditor presenter, ILanguage highlightLanguage)
{
var highlighterName = "";
if (highlightLanguage == Languages.CSharp)
{
highlighterName = "C#";
}
else if (highlightLanguage == Languages.Xml)
{
highlighterName = "XML";
}
var highlighter = HighlightingManager.Instance.GetDefinition(highlighterName);
if (presenter.SyntaxHighlighting != highlighter)
presenter.SyntaxHighlighting = highlighter;
var formattedText = StringHelper.RemoveLeadingAndTrailingEmptyLines(sampleString);
if (formattedText != presenter.Text)
presenter.Text = formattedText;
presenter.Visibility = Visibility.Visible;
}
private void CopyCodeButton_Click(object sender, RoutedEventArgs e)
{
try
{
Clipboard.SetText(CodePresenter.Text);
VisualStateManager.GoToState(this, "ConfirmationDialogVisible", false);
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString(), "Unable to Perform Copy", MessageBoxButton.OK, MessageBoxImage.Error);
}
// Automatically close teachingtip after 1 seconds
this.RunOnUIThread(async () =>
{
await Task.Delay(1000);
VisualStateManager.GoToState(this, "ConfirmationDialogHidden", false);
});
}
private void FixAvalonEditScrolling()
{
var scv = CodePresenter.Template.FindName("PART_ScrollViewer", CodePresenter);
if (scv is ScrollViewer PART_ScrollViewer)
{
// I don't know why AvalonEditor doesn't handle horizontal scrolling properly,
// So we see horizontal scrolls as vertical scrolls and bubble it to the parent.
PART_ScrollViewer.PreviewMouseWheel += (sender, e) =>
{
var eventArg = new MouseWheelEventArgs(e.MouseDevice, e.Timestamp, e.Delta);
eventArg.RoutedEvent = UIElement.MouseWheelEvent;
eventArg.Source = sender;
this.RaiseEvent(eventArg);
};
}
}
}
}