Skip to content

Commit cf3f807

Browse files
author
ArthurHub
committed
fix html clipblorad data string format creation
1 parent 3421018 commit cf3f807

2 files changed

Lines changed: 145 additions & 61 deletions

File tree

‎Source/HtmlRenderer/Handlers/SelectionHandler.cs‎

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -171,7 +171,7 @@ public void SelectWord(Control control, Point loc)
171171
public void HandleMouseDown(Control parent, Point loc, bool isMouseInContainer)
172172
{
173173
bool clear = !isMouseInContainer;
174-
if(isMouseInContainer)
174+
if (isMouseInContainer)
175175
{
176176
_mouseDownInControl = true;
177177
_isDoubleClickSelect = (DateTime.Now - _lastMouseDown).TotalMilliseconds < 400;
@@ -194,7 +194,7 @@ public void HandleMouseDown(Control parent, Point loc, bool isMouseInContainer)
194194
{
195195
var rect = DomUtils.GetCssBoxWord(_root, loc);
196196
var link = DomUtils.GetLinkBox(_root, loc);
197-
if(_root.HtmlContainer.IsContextMenuEnabled)
197+
if (_root.HtmlContainer.IsContextMenuEnabled)
198198
{
199199
_contextMenuHandler.ShowContextMenu(parent, rect, link);
200200
}
@@ -234,7 +234,7 @@ public bool HandleMouseUp(Control parent, MouseButtons button)
234234
ignore = ignore || (DateTime.Now - _lastMouseDown > TimeSpan.FromSeconds(1));
235235
return ignore;
236236
}
237-
237+
238238
/// <summary>
239239
/// Handle mouse move to handle hover cursor and text selection.
240240
/// </summary>
@@ -268,23 +268,23 @@ public void HandleMouseMove(Control parent, Point loc)
268268
else if (_root.HtmlContainer.IsSelectionEnabled)
269269
{
270270
var word = DomUtils.GetCssBoxWord(_root, loc);
271-
_cursorChanged = word != null && !word.IsImage && !( word.Selected && ( word.SelectedStartIndex < 0 || word.Left + word.SelectedStartOffset <= loc.X ) && ( word.SelectedEndOffset < 0 || word.Left + word.SelectedEndOffset >= loc.X ) );
271+
_cursorChanged = word != null && !word.IsImage && !(word.Selected && (word.SelectedStartIndex < 0 || word.Left + word.SelectedStartOffset <= loc.X) && (word.SelectedEndOffset < 0 || word.Left + word.SelectedEndOffset >= loc.X));
272272
parent.Cursor = _cursorChanged ? Cursors.IBeam : Cursors.Default;
273273
}
274-
else if(_cursorChanged)
274+
else if (_cursorChanged)
275275
{
276-
parent.Cursor = Cursors.Default;
276+
parent.Cursor = Cursors.Default;
277277
}
278278
}
279279
}
280-
280+
281281
/// <summary>
282282
/// On mouse leave change the cursor back to default.
283283
/// </summary>
284284
/// <param name="parent">the control hosting the html to set cursor and invalidate</param>
285285
public void HandleMouseLeave(Control parent)
286286
{
287-
if(_cursorChanged)
287+
if (_cursorChanged)
288288
{
289289
_cursorChanged = false;
290290
parent.Cursor = Cursors.Default;
@@ -297,12 +297,12 @@ public void HandleMouseLeave(Control parent)
297297
/// </summary>
298298
public void CopySelectedHtml()
299299
{
300-
if(_root.HtmlContainer.IsSelectionEnabled)
300+
if (_root.HtmlContainer.IsSelectionEnabled)
301301
{
302302
var html = DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true);
303303
var plainText = DomUtils.GetSelectedPlainText(_root);
304304
if (!string.IsNullOrEmpty(plainText))
305-
HtmlClipboardUtils.CopyToClipboard(html, plainText);
305+
ClipboardHelper.CopyToClipboard(html, plainText);
306306
}
307307
}
308308

@@ -504,7 +504,7 @@ private void StartDragDrop(Control control)
504504
{
505505
var html = DomUtils.GenerateHtml(_root, HtmlGenerationStyle.Inline, true);
506506
var plainText = DomUtils.GetSelectedPlainText(_root);
507-
_dragDropData = HtmlClipboardUtils.GetDataObject(html, plainText);
507+
_dragDropData = ClipboardHelper.CreateDataObject(html, plainText);
508508
}
509509
control.DoDragDrop(_dragDropData, DragDropEffects.Copy);
510510
}
@@ -610,7 +610,7 @@ private void CalculateWordCharIndexAndOffset(Control control, CssRect word, Poin
610610
float selectionOffset;
611611
CalculateWordCharIndexAndOffset(control, word, loc, selectionStart, _root.HtmlContainer.UseGdiPlusTextRendering, out selectionIndex, out selectionOffset);
612612

613-
if(selectionStart)
613+
if (selectionStart)
614614
{
615615
_selectionStartIndex = selectionIndex;
616616
_selectionStartOffset = selectionOffset;
@@ -661,7 +661,7 @@ private static void CalculateWordCharIndexAndOffset(Control control, CssRect wor
661661
{
662662
int charFit;
663663
int charFitWidth;
664-
var maxWidth = offset + ( inclusive ? 0 : 1.5f*word.LeftGlyphPadding );
664+
var maxWidth = offset + (inclusive ? 0 : 1.5f * word.LeftGlyphPadding);
665665
g.MeasureString(word.Text, font, maxWidth, out charFit, out charFitWidth);
666666

667667
selectionIndex = charFit;

‎Source/HtmlRenderer/Utils/HtmlClipboardUtils.cs‎

Lines changed: 132 additions & 48 deletions
Original file line numberDiff line numberDiff line change
@@ -10,96 +10,180 @@
1010
namespace HtmlRenderer.Utils
1111
{
1212
/// <summary>
13-
/// Helper class to decode HTML from the clipboard.
14-
/// See http://blogs.msdn.com/jmstall/archive/2007/01/21/html-clipboard.aspx for details.
13+
/// Helper to encode and set HTML fragment to clipboard.<br/>
14+
/// See http://theartofdev.wordpress.com/2012/11/11/setting-html-and-plain-text-formatting-to-clipboard/.<br/>
15+
/// <seealso cref="CreateDataObject"/>.
1516
/// </summary>
16-
internal static class HtmlClipboardUtils
17+
internal static class ClipboardHelper
1718
{
1819
#region Fields and Consts
1920

2021
/// <summary>
2122
/// The string contains index references to other spots in the string, so we need placeholders so we can compute the offsets. <br/>
22-
/// The <![CDATA[<<<<<<<]]>_ strings are just placeholders. We'll backpatch them actual values afterwards. <br/>
23+
/// The <![CDATA[<<<<<<<]]>_ strings are just placeholders. We'll back-patch them actual values afterwards. <br/>
2324
/// The string layout (<![CDATA[<<<]]>) also ensures that it can't appear in the body of the html because the <![CDATA[<]]> <br/>
2425
/// character must be escaped. <br/>
2526
/// </summary>
2627
private const string Header = @"Format:HTML Format
27-
Version:1.0
28-
StartHTML:<<<<<<<1
29-
EndHTML:<<<<<<<2
30-
StartFragment:<<<<<<<3
31-
EndFragment:<<<<<<<4
32-
StartSelection:<<<<<<<3
33-
EndSelection:<<<<<<<3
34-
";
28+
Version:1.0
29+
StartHTML:<<<<<<<1
30+
EndHTML:<<<<<<<2
31+
StartFragment:<<<<<<<3
32+
EndFragment:<<<<<<<4
33+
StartSelection:<<<<<<<3
34+
EndSelection:<<<<<<<3";
35+
36+
/// <summary>
37+
/// html comment to point the beginning of html fragment
38+
/// </summary>
39+
public const string StartFragment = "<!--StartFragment-->";
40+
41+
/// <summary>
42+
/// html comment to point the end of html fragment
43+
/// </summary>
44+
public const string EndFragment = @"<!--EndFragment-->";
3545

3646
#endregion
3747

3848

3949
/// <summary>
40-
/// Get data object with given html and plaintext ready to be used for clipboard or drag & drop.
50+
/// Create <see cref="DataObject"/> with given html and plain-text ready to be used for clipboard or drag and drop.
4151
/// </summary>
52+
/// <remarks>
53+
/// Builds the CF_HTML header correctly for all possible HTMLs<br/>
54+
/// If given html contains start/end fragments then it will use them in the header:
55+
/// <code><![CDATA[<html><body><!--StartFragment-->hello <b>world</b><!--EndFragment--></body></html>]]></code>
56+
/// If given html contains html/body tags then it will inject start/end fragments to exclude html/body tags:
57+
/// <code><![CDATA[<html><body>hello <b>world</b></body></html>]]></code>
58+
/// If given html doesn't contain html/body tags then it will inject the tags and start/end fragments properly:
59+
/// <code><![CDATA[hello <b>world</b>]]></code>
60+
/// In all cases creating a proper CF_HTML header:<br/>
61+
/// <code>
62+
/// <![CDATA[
63+
/// Format:HTML Format
64+
/// Version:1.0
65+
/// StartHTML: 177
66+
/// EndHTML: 329
67+
/// StartFragment: 277
68+
/// EndFragment: 295
69+
/// StartSelection: 277
70+
/// EndSelection: 277
71+
/// <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
72+
/// <html><body>
73+
/// <!--StartFragment-->hello <b>world</b><!--EndFragment-->
74+
/// </body></html>
75+
/// ]]>
76+
/// </code>
77+
/// See format specification here: http://msdn.microsoft.com/library/default.asp?url=/workshop/networking/clipboard/htmlclipboard.asp
78+
/// </remarks>
4279
/// <param name="html">a html fragment</param>
4380
/// <param name="plainText">the plain text</param>
44-
public static DataObject GetDataObject(string html, string plainText)
81+
public static DataObject CreateDataObject(string html, string plainText)
4582
{
46-
var data = GetHtmlData(html);
4783
var dataObject = new DataObject();
48-
dataObject.SetData(DataFormats.Html, data);
84+
dataObject.SetData(DataFormats.Html, !string.IsNullOrEmpty(html) ? GetHtmlDataString(html) : html);
4985
dataObject.SetData(DataFormats.Text, plainText);
5086
return dataObject;
5187
}
5288

5389
/// <summary>
54-
/// Clears clipboard and copy a HTML fragment to the clipboard, providing additional meta-information.
90+
/// Clears clipboard and sets the given HTML and plain text fragment to the clipboard, providing additional meta-information for HTML.<br/>
91+
/// See <see cref="CreateDataObject"/> for HTML fragment details.<br/>
5592
/// </summary>
56-
/// <remarks>
57-
/// Builds the CF_HTML header. See format specification here:
58-
/// http://msdn.microsoft.com/library/default.asp?url=/workshop/networking/clipboard/htmlclipboard.asp
59-
/// </remarks>
6093
/// <example>
61-
/// HtmlClipboardUtils.CopyToClipboard("<b>Hello!</b>");
94+
/// ClipboardHelper.CopyToClipboard("Hello <b>World</b>", "Hello World");
6295
/// </example>
6396
/// <param name="html">a html fragment</param>
6497
/// <param name="plainText">the plain text</param>
6598
public static void CopyToClipboard(string html, string plainText)
6699
{
67-
Clipboard.SetDataObject(GetDataObject(html, plainText));
100+
var dataObject = CreateDataObject(html, plainText);
101+
Clipboard.SetDataObject(dataObject);
68102
}
69103

70-
71-
#region Private methods
72-
73104
/// <summary>
74-
/// Generate format html string with header that is required for the clipboard.
105+
/// Generate HTML fragment data string with header that is required for the clipboard.
75106
/// </summary>
76107
/// <param name="html">the html to generate for</param>
77108
/// <returns>the resulted string</returns>
78-
private static string GetHtmlData(string html)
109+
private static string GetHtmlDataString(string html)
79110
{
80111
var sb = new StringBuilder();
81-
82-
sb.Append(Header);
83-
int startHtml = sb.Length;
84-
85-
sb.Append(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN""><!--StartFragment-->");
86-
int fragmentStart = sb.Length;
87-
88-
sb.Append(html);
89-
int fragmentEnd = sb.Length;
90-
91-
sb.Append(@"<!--EndFragment-->");
92-
int endHtml = sb.Length;
93-
94-
// Backpatch offsets
95-
sb.Replace("<<<<<<<1", String.Format("{0,8}", startHtml));
96-
sb.Replace("<<<<<<<2", String.Format("{0,8}", endHtml));
97-
sb.Replace("<<<<<<<3", String.Format("{0,8}", fragmentStart));
98-
sb.Replace("<<<<<<<4", String.Format("{0,8}", fragmentEnd));
112+
sb.AppendLine(Header);
113+
sb.AppendLine(@"<!DOCTYPE HTML PUBLIC ""-//W3C//DTD HTML 4.0 Transitional//EN"">");
114+
115+
// if given html already provided the fragments we won't add them
116+
int fragmentStart, fragmentEnd;
117+
int fragmentStartIdx = html.IndexOf(StartFragment, StringComparison.OrdinalIgnoreCase);
118+
int fragmentEndIdx = html.LastIndexOf(EndFragment, StringComparison.OrdinalIgnoreCase);
119+
if (fragmentStartIdx < 0 && fragmentEndIdx < 0)
120+
{
121+
int htmlOpenIdx = html.IndexOf("<html", StringComparison.OrdinalIgnoreCase);
122+
int bodyOpenIdx = html.IndexOf("<body", StringComparison.OrdinalIgnoreCase);
123+
int htmlOpenEndIdx = htmlOpenIdx > -1 ? html.IndexOf('>', htmlOpenIdx) + 1 : -1;
124+
int bodyOpenEndIdx = bodyOpenIdx > -1 ? html.IndexOf('>', bodyOpenIdx) + 1 : -1;
125+
126+
if (htmlOpenEndIdx < 0 && bodyOpenEndIdx < 0)
127+
{
128+
// the given html doesn't contain html or body tags so we need to add them and place start/end fragments around the given html only
129+
sb.Append("<html><body>");
130+
sb.AppendLine();
131+
sb.Append(StartFragment);
132+
fragmentStart = sb.Length;
133+
sb.Append(html);
134+
fragmentEnd = sb.Length;
135+
sb.Append(EndFragment);
136+
sb.AppendLine();
137+
sb.Append("</body></html>");
138+
}
139+
else
140+
{
141+
// if html tag is missing add it surrounding the given html (critical)
142+
// insert start/end fragments in the proper place (related to html/body tags if exists) so the paste will work correctly
143+
int htmlCloseIdx = html.LastIndexOf("</html", StringComparison.OrdinalIgnoreCase);
144+
int bodyCloseIdx = html.LastIndexOf("</body", StringComparison.OrdinalIgnoreCase);
145+
146+
if (htmlOpenEndIdx < 0)
147+
sb.Append("<html>");
148+
else
149+
sb.Append(html, 0, htmlOpenEndIdx);
150+
151+
if (bodyOpenEndIdx > -1)
152+
sb.Append(html, htmlOpenEndIdx > -1 ? htmlOpenEndIdx : 0, bodyOpenEndIdx - (htmlOpenEndIdx > -1 ? htmlOpenEndIdx : 0));
153+
154+
sb.AppendLine();
155+
sb.Append(StartFragment);
156+
fragmentStart = sb.Length;
157+
158+
var innerHtmlStart = bodyOpenEndIdx > -1 ? bodyOpenEndIdx : (htmlOpenEndIdx > -1 ? htmlOpenEndIdx : 0);
159+
var innerHtmlEnd = bodyCloseIdx > -1 ? bodyCloseIdx : (htmlCloseIdx > -1 ? htmlCloseIdx : html.Length);
160+
sb.Append(html, innerHtmlStart, innerHtmlEnd - innerHtmlStart);
161+
162+
fragmentEnd = sb.Length;
163+
sb.Append(EndFragment);
164+
sb.AppendLine();
165+
166+
if (innerHtmlEnd < html.Length)
167+
sb.Append(html, innerHtmlEnd, html.Length - innerHtmlEnd);
168+
169+
if (htmlCloseIdx < 0)
170+
sb.Append("</html>");
171+
}
172+
}
173+
else
174+
{
175+
fragmentStart = sb.Length + fragmentStartIdx + StartFragment.Length;
176+
fragmentEnd = sb.Length + fragmentEndIdx;
177+
sb.Append(html);
178+
}
179+
180+
// Back-patch offsets (scan only the header part for performance)
181+
sb.Replace("<<<<<<<4", String.Format("{0,8}", fragmentEnd), 0, Header.Length);
182+
sb.Replace("<<<<<<<3", String.Format("{0,8}", fragmentStart), 0, Header.Length);
183+
sb.Replace("<<<<<<<2", String.Format("{0,8}", sb.Length), 0, Header.Length);
184+
sb.Replace("<<<<<<<1", String.Format("{0,8}", Header.Length), 0, Header.Length);
99185

100186
return sb.ToString();
101187
}
102-
103-
#endregion
104188
}
105189
}

0 commit comments

Comments
 (0)