-
Notifications
You must be signed in to change notification settings - Fork 0
/
CKEditor.xaml.cs
282 lines (237 loc) · 9.75 KB
/
CKEditor.xaml.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
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
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Threading;
using System.Web.Script.Serialization;
using System.Windows;
using System.Windows.Forms.Integration;
using System.Windows.Threading;
using CefSharp;
using CefSharp.WinForms;
namespace BrightSharp.Toolkit.Extra
{
public partial class CKEditor
{
internal ChromiumWebBrowser Browser;
private CKEditorObjectForScripting _objectForScripting;
public static void InitializeCef(bool useCache = true, bool reinit = false)
{
Dispatcher.CurrentDispatcher.ShutdownStarted += (s, e) => Cef.Shutdown();
if (!reinit && Cef.IsInitialized) return;
CefSettings settings;
if (useCache)
{
var cacheDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
"cefCache");
Directory.CreateDirectory(cacheDir);
settings = new CefSettings
{
CachePath = cacheDir
};
}
else
{
settings = new CefSettings();
}
settings.RegisterScheme(new CefCustomScheme
{
SchemeName = "local",
SchemeHandlerFactory = new FolderSchemeHandlerFactory(Environment.CurrentDirectory)
});
Cef.Initialize(settings);
}
private static void InitializeDesignTimeDirectory()
{
if (DesignerProperties.GetIsInDesignMode(new DependencyObject()))
{
Environment.CurrentDirectory = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
var nugetPackages = DesignTimeConfig.GetNugetPackagesDirectory();
if (!Directory.Exists(nugetPackages)) return;
var prefix = IntPtr.Size == 4 ? "x86" : "x64";
var allDirectoriesToCopy = Directory.GetDirectories(nugetPackages, "cef.redist.*")
.Union(Directory.GetDirectories(nugetPackages, "CefSharp.*"))
.SelectMany(d => Directory.GetDirectories(d, prefix, SearchOption.AllDirectories));
foreach (var dirForCopy in allDirectoriesToCopy)
{
foreach (var file in Directory.GetFiles(dirForCopy))
{
try { File.Copy(file, Path.Combine(Environment.CurrentDirectory, Path.GetFileName(file)), false); }
catch (Exception) { }
}
foreach (var file in Directory.GetFiles(Directory.GetParent(dirForCopy).FullName))
{
try { File.Copy(file, Path.Combine(Environment.CurrentDirectory, Path.GetFileName(file)), false); }
catch (Exception) { }
}
}
}
}
static CKEditor()
{
InitializeDesignTimeDirectory();
if (!File.Exists("CefSharp.Core.dll"))
return;
InitializeCef();
}
public CKEditor()
{
InitializeComponent();
}
public override void OnApplyTemplate()
{
if (!File.Exists("CefSharp.dll"))
return;
var host = (WindowsFormsHost)Template.FindName("PART_Host", this);
host.Child = Browser = new ChromiumWebBrowser("about:blank");
_objectForScripting = new CKEditorObjectForScripting(this);
Browser.KeyboardHandler = new FixKeyboardHandler();
Browser.IsBrowserInitializedChanged += (s, e) =>
{
if (e.IsBrowserInitialized)
RefreshState();
};
base.OnApplyTemplate();
}
public void RefreshState()
{
if (Browser != null && Browser.IsBrowserInitialized)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
var docContent = BuildDocContent();
Browser.LoadString(docContent, "about:blank");
}));
UpdateDevToolsState();
}
}
protected override void OnContentChanged(object oldContent, object newContent)
{
if (Browser != null && _objectForScripting != null && (string)newContent != _objectForScripting.NewData)
{
//This is not from js
Browser.EvaluateScriptAsync($"setData(`{newContent}`)").Wait(TimeSpan.FromSeconds(2));
}
base.OnContentChanged(oldContent, newContent);
}
public string PackageType
{
get { return (string)GetValue(PackageTypeProperty); }
set { SetValue(PackageTypeProperty, value); }
}
public static readonly DependencyProperty PackageTypeProperty =
DependencyProperty.Register("PackageType", typeof(string), typeof(CKEditor), new PropertyMetadata("standard", UpdatePackageType));
private static void UpdatePackageType(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var editor = (CKEditor)d;
editor.RefreshState();
}
public bool ShowDevTools
{
get { return (bool)GetValue(ShowDevToolsProperty); }
set { SetValue(ShowDevToolsProperty, value); }
}
public static readonly DependencyProperty ShowDevToolsProperty =
DependencyProperty.Register("ShowDevTools", typeof(bool), typeof(CKEditor), new PropertyMetadata(false, ShowDevToolsChanged));
private static void ShowDevToolsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var editor = (CKEditor)d;
editor.UpdateDevToolsState();
}
private void UpdateDevToolsState()
{
if (Browser != null && Browser.IsBrowserInitialized)
{
Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() =>
{
if (ShowDevTools)
Browser.ShowDevTools();
else
Browser.CloseDevTools();
}));
}
}
private string BuildDocContent()
{
var docContent = Properties.Resources.HtmlEditor;
if (EditorConfiguration != null)
{
EditorConfiguration.Optimize(PackageType);
docContent = docContent.Replace("$$CONFIG",
new JavaScriptSerializer().Serialize(EditorConfiguration));
docContent = docContent.Replace("$$PACKAGE", PackageType);
}
docContent = docContent.Replace("$$CONTENT", (Content ?? "").ToString());
return docContent;
}
public CKEditorConfig EditorConfiguration
{
get { return (CKEditorConfig)GetValue(EditorConfigurationProperty); }
set { SetValue(EditorConfigurationProperty, value); }
}
public static readonly DependencyProperty EditorConfigurationProperty =
DependencyProperty.Register("EditorConfiguration", typeof(CKEditorConfig), typeof(CKEditor), new PropertyMetadata(new CKEditorConfig()));
}
[SuppressMessage("ReSharper", "InconsistentNaming")]
public class CKEditorConfig
{
public string[] contentsCss { get; set; }
public string language { get; set; } = Thread.CurrentThread.CurrentUICulture.Name;
public string removeButtons { get; set; } =
"Save,Print,Preview,Maximize,ShowBlocks,Paste,PasteText,PasteFromWord";
public string extraAllowedContent { get; set; } = "span;ul;li;table;td;style;*[id];*(*);*{*}";
public string removePlugins { get; set; } = "resize";
public void Optimize(string packageType)
{
if (string.Equals("basic", packageType, StringComparison.InvariantCultureIgnoreCase))
{
//TODO Basic configuration has many problems.
//TODO Need think do we need it, or can we use Standard package as Basic to emulate Basic (from CKE) ?
}
}
}
internal class CKEditorObjectForScripting
{
private CKEditor _editor;
internal string NewData;
public CKEditorObjectForScripting(CKEditor editor)
{
_editor = editor;
_editor.Browser.RegisterJsObject("$$OBJ", this);
}
[SuppressMessage("ReSharper", "UnusedMember.Global")]
public void SetupContent(string newData)
{
NewData = newData;
_editor.Dispatcher.BeginInvoke(DispatcherPriority.Normal, new Action(() => _editor.Content = NewData));
}
}
public class CKEditorDesignTimeSettings
{
public static string DesignTimeCefBinariesDirectory { get; set; }
}
class FixKeyboardHandler : IKeyboardHandler
{
public bool OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode,
CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut)
{
//F10, Alt
if (windowsKeyCode == 0x79 || windowsKeyCode == 0x12)
{
return true;
}
return false;
}
public bool OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode,
CefEventFlags modifiers, bool isSystemKey)
{
if (windowsKeyCode == 0x79 || windowsKeyCode == 0x12)
{
return true;
}
return false;
}
}
}