File size: 9,996 Bytes
fab29d7
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using System.IO.Packaging;
using System.Windows;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using TheArtOfDev.HtmlRenderer.Core.Entities;
using TheArtOfDev.HtmlRenderer.WPF;
using VersOne.Epub.WpfDemo.ViewModels;

namespace VersOne.Epub.WpfDemo.Controls
{
    /// <summary>
    /// WPF control that renders a single HTML content file of a EPUB book.
    /// </summary>
    public class BookHtmlContent : HtmlPanel
    {
        /// <summary>
        /// Identifies the <see cref="EpubArchive" /> dependency property.
        /// </summary>
        public static readonly DependencyProperty EpubArchiveProperty = DependencyProperty.Register("EpubArchive", typeof(ZipArchive), typeof(BookHtmlContent));

        /// <summary>
        /// Identifies the <see cref="HtmlContentFile" /> dependency property.
        /// </summary>
        public static readonly DependencyProperty HtmlContentFileProperty =
            DependencyProperty.Register("HtmlContentFile", typeof(HtmlContentFileViewModel), typeof(BookHtmlContent), new PropertyMetadata(OnHtmlContentFileChanged));

        /// <summary>
        /// Identifies the <see cref="Anchor" /> dependency property.
        /// </summary>
        public static readonly DependencyProperty AnchorProperty = DependencyProperty.Register("Anchor", typeof(string), typeof(BookHtmlContent), new PropertyMetadata(OnAnchorChanged));

        private bool areFontsRegistered;
        private bool isContentLoaded;
        private string queuedScrollToAnchor;

        /// <summary>
        /// Initializes a new instance of the <see cref="BookHtmlContent" /> class.
        /// </summary>
        public BookHtmlContent()
        {
            areFontsRegistered = false;
            isContentLoaded = false;
            queuedScrollToAnchor = null;
        }

        /// <summary>
        /// Gets or sets the EPUB archive that contains the HTML content file that needs to be rendered.
        /// </summary>
        public ZipArchive EpubArchive
        {
            get
            {
                return (ZipArchive)GetValue(EpubArchiveProperty);
            }
            set
            {
                SetValue(EpubArchiveProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the HTML content file that needs to be rendered.
        /// </summary>
        public HtmlContentFileViewModel HtmlContentFile
        {
            get
            {
                return (HtmlContentFileViewModel)GetValue(HtmlContentFileProperty);
            }
            set
            {
                SetValue(HtmlContentFileProperty, value);
            }
        }

        /// <summary>
        /// Gets or sets the anchor inside the HTML content file that needs to be scrolled to once the content is fully loaded.
        /// </summary>
        public string Anchor
        {
            get
            {
                return (string)GetValue(AnchorProperty);
            }
            set
            {
                SetValue(AnchorProperty, value);
            }
        }

        /// <summary>
        /// Loads the content of the image from the EPUB archive.
        /// </summary>
        /// <param name="e">An event parameter identifying the image that needs to be loaded.</param>
        protected override void OnImageLoad(HtmlImageLoadEventArgs e)
        {
            byte[] imageContent = GetImageContent(e.Src);
            if (imageContent != null)
            {
                using (MemoryStream imageStream = new MemoryStream(imageContent))
                {
                    BitmapImage bitmapImage = new BitmapImage();
                    bitmapImage.BeginInit();
                    bitmapImage.StreamSource = imageStream;
                    bitmapImage.CacheOption = BitmapCacheOption.OnLoad;
                    bitmapImage.EndInit();
                    bitmapImage.Freeze();
                    e.Callback(bitmapImage);
                }
                e.Handled = true;
            }
            base.OnImageLoad(e);
        }

        /// <summary>
        /// Loads the content of the CSS stylesheet from the EPUB archive.
        /// </summary>
        /// <param name="e">An event parameter identifying the CSS stylesheet that needs to be loaded.</param>
        protected override void OnStylesheetLoad(HtmlStylesheetLoadEventArgs e)
        {
            string styleSheetContent = GetStyleSheetContent(e.Src);
            if (styleSheetContent != null)
            {
                e.SetStyleSheet = styleSheetContent;
            }
            base.OnStylesheetLoad(e);
        }

        /// <summary>
        /// Scrolls the rendered HTML content to the <see cref="Anchor" /> if needed.
        /// </summary>
        /// <param name="e">An parameter containing event data.</param>
        protected override void OnLoadComplete(EventArgs e)
        {
            base.OnLoadComplete(e);
            if (queuedScrollToAnchor != null)
            {
                ScrollToElement(queuedScrollToAnchor);
                queuedScrollToAnchor = null;
            }
            isContentLoaded = true;
        }

        private static void OnAnchorChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            if (!(dependencyObject is BookHtmlContent bookHtmlContent) || bookHtmlContent.HtmlContentFile == null || bookHtmlContent.Anchor == null)
            {
                return;
            }
            if (bookHtmlContent.isContentLoaded)
            {
                bookHtmlContent.ScrollToElement(bookHtmlContent.Anchor);
            }
            else
            {
                bookHtmlContent.queuedScrollToAnchor = bookHtmlContent.Anchor;
            }
        }

        private static void OnHtmlContentFileChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            if (!(dependencyObject is BookHtmlContent bookHtmlContent) || bookHtmlContent.HtmlContentFile == null)
            {
                return;
            }
            if (!bookHtmlContent.areFontsRegistered)
            {
                bookHtmlContent.RegisterFonts();
            }
            bookHtmlContent.isContentLoaded = false;
            bookHtmlContent.queuedScrollToAnchor = null;
            bookHtmlContent.Text = bookHtmlContent.HtmlContentFile.HtmlContent;
        }

        private byte[] GetImageContent(string imageFilePath)
        {
            if (HtmlContentFile.Images.TryGetValue(GetFullPath(HtmlContentFile.HtmlFilePathInEpubManifest, imageFilePath), out byte[] imageContent))
            {
                return imageContent;
            }
            ZipArchiveEntry zipArchiveEntry = EpubArchive.GetEntry(GetFullPath(HtmlContentFile.HtmlFilePathInEpubArchive, imageFilePath));
            if (zipArchiveEntry != null)
            {
                imageContent = new byte[(int)zipArchiveEntry.Length];
                using (Stream zipArchiveEntryStream = zipArchiveEntry.Open())
                using (MemoryStream memoryStream = new MemoryStream(imageContent))
                {
                    zipArchiveEntryStream.CopyTo(memoryStream);
                }
                return imageContent;
            }
            return null;
        }

        private string GetStyleSheetContent(string styleSheetFilePath)
        {
            if (HtmlContentFile.StyleSheets.TryGetValue(GetFullPath(HtmlContentFile.HtmlFilePathInEpubManifest, styleSheetFilePath), out string styleSheetContent))
            {
                return styleSheetContent;
            }
            ZipArchiveEntry zipArchiveEntry = EpubArchive.GetEntry(GetFullPath(HtmlContentFile.HtmlFilePathInEpubArchive, styleSheetFilePath));
            if (zipArchiveEntry != null)
            {
                using (Stream zipArchiveEntryStream = zipArchiveEntry.Open())
                using (StreamReader streamReader = new StreamReader(zipArchiveEntryStream))
                {
                    styleSheetContent = streamReader.ReadToEnd();
                }
                return styleSheetContent;
            }
            return null;
        }

        private string GetFullPath(string htmlFilePath, string relativePath)
        {
            if (relativePath.StartsWith("/"))
            {
                return relativePath.Length > 1 ? relativePath.Substring(1) : String.Empty;
            }
            string basePath = Path.GetDirectoryName(htmlFilePath);
            while (relativePath.StartsWith("../"))
            {
                relativePath = relativePath.Length > 3 ? relativePath.Substring(3) : String.Empty;
                basePath = Path.GetDirectoryName(basePath);
            }
            string fullPath = String.Concat(basePath.Replace('\\', '/'), '/', relativePath).TrimStart('/');
            return fullPath;
        }

        private void RegisterFonts()
        {
            foreach (KeyValuePair<string, byte[]> fontFile in HtmlContentFile.Fonts)
            {
                MemoryStream packageStream = new MemoryStream();
                Package package = Package.Open(packageStream, FileMode.Create, FileAccess.ReadWrite);
                Uri packageUri = new Uri("fonts://" + fontFile.Key);
                PackageStore.AddPackage(packageUri, package);
                Uri packPartUri = new Uri("/content", UriKind.Relative);
                PackagePart packPart = package.CreatePart(packPartUri, "font/content");
                packPart.GetStream().Write(fontFile.Value, 0, fontFile.Value.Length);
                Uri fontUri = PackUriHelper.Create(packageUri, packPart.Uri);
                foreach (FontFamily fontFamily in Fonts.GetFontFamilies(fontUri))
                {
                    HtmlRender.AddFontFamily(fontFamily);
                }
            }
            areFontsRegistered = true;
        }
    }
}