Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

C.B.R.

, 22 Oct 2012
Comic and electronic publication reader with library management, extended file conversion, and devices support.
CBR.zip
Release
CBR.Core.dll
CBR.exe
Dependencies
7z.dll
Fluent.dll
itextsharp.dll
Microsoft.Expression.Drawing.dll
Microsoft.Expression.Interactions.dll
SevenZipSharp.dll
System.Windows.Interactivity.dll
cbr0_5.zip
Languages
flag_france.png
flag_great_britain.png
Dependencies
7z.dll
cbrz.ico
epub.ico
pdf.ico
rar.ico
cbr_0_3-source.zip
CBR
CBR.Core
Dependencies
7z.dll
CoreDiagram.cd
itextsharp.dll
SevenZipSharp.dll
Files
Conversion
IMG
PDF
RAR
XPS
Helpers
MVVM
Commands
Events
Messages
Models
Workspace
Properties
Services
Book
CBR
Components
Controls
Converters
Designer
Adorners
Dialogs
Helpers
Dependencies
Fluent.dll
ProgrammDiagram.cd
Properties
Settings.settings
Resources
Images
16x16
pin_no.png
pin_yes.png
sort_alpha.png
sort_category.png
view_details.png
view_thumb.png
32x32
book.png
book_add.png
book_close.png
book_convert.png
book_delete.png
book_edit.png
book_open.png
book_protect.png
book_read.png
book_save.png
book_test.png
book_type_none.png
book_type_rar.png
book_type_xps.png
book_type_zip.png
exit.png
fit_height.png
fit_width.png
forbidden.png
full_screen.png
help.png
info.png
library_close.png
library_new.png
library_open.png
library_view.png
open_folder.png
page_clear_mark.png
page_goto_mark.png
page_mark.png
page_test.png
picture_order.png
picture_time.png
picture_zone.png
push_pin.png
read.png
refresh.png
save.png
save_as.png
tools.png
book.ico
phone_horizontal.png
search.png
XAML
Controls
ViewModels
Book
Explorer
File
Views
Books
File
cbr_0_4-source.zip
BookReader
BookReader.vssscc
BookReader
BookReader.csproj.vspscc
Common
Controls
Dependencies
7z.dll
pdftohtml.exe
SevenZipSharp.dll
WPFToolkit.dll
Dialogs
Properties
app.manifest
Settings.settings
Reader
Catalog
Common
Images
RAR
Resources
book.ico
Images
acroread.png
document.png
ecran.png
exit.png
filter.png
FitHeight.png
FitWidth.png
forbidden.png
GotoPage.png
info.png
open_folder.png
protect.png
refresh.png
Search.png
Style.png
TheRedPushPin.png
tools.png
Themes
Black
Blue
Silver
XAML
BuildProcessTemplates
CBR.Core.csproj.vspscc
7z.dll
CoreDiagram.cd
itextsharp.dll
SevenZipSharp.dll
DragDrop
ePUB
HTML
WMI
XPS
ePUB
Books
CBR.vssscc
CBR.csproj.vspscc
Devices.xlsx
Fluent.dll
ProgrammDiagram.cd
Settings.settings
disk.png
file.png
folder.png
pin_no.png
pin_yes.png
sort_alpha.png
sort_category.png
view_details.png
view_thumb.png
book.png
book_add.png
book_close.png
book_convert.png
book_delete.png
book_edit.png
book_open.png
book_protect.png
book_read.png
book_remove.png
book_save.png
book_test.png
book_type_epub.png
book_type_none.png
book_type_rar.png
book_type_xps.png
book_type_zip.png
device_refresh.png
device_sync.png
device_view.png
exit.png
fit_height.png
fit_width.png
forbidden.png
full_screen.png
help.png
info.png
library_close.png
library_new.png
library_open.png
library_view.png
open_folder.png
page_clear_mark.png
page_first.png
page_goto_mark.png
page_last.png
page_mark.png
page_next.png
page_previous.png
page_test.png
picture_order.png
picture_time.png
picture_zone.png
push_pin.png
read.png
refresh.png
save.png
save_as.png
tools.png
book.ico
phone_horizontal.png
search.png
Books
Devices
SysItems
Devices
cbr_0_5-source.zip
BookReader.vssscc
BookReader.csproj.vspscc
7z.dll
pdftohtml.exe
SevenZipSharp.dll
WPFToolkit.dll
app.manifest
Settings.settings
book.ico
acroread.png
document.png
ecran.png
exit.png
filter.png
FitHeight.png
FitWidth.png
forbidden.png
GotoPage.png
info.png
open_folder.png
protect.png
refresh.png
Search.png
Style.png
TheRedPushPin.png
tools.png
CBR.Core.csproj.vspscc
7z.dll
cbrz.ico
CoreDiagram.cd
epub.ico
itextsharp.dll
pdf.ico
rar.ico
SevenZipSharp.dll
Files
Localization
Core
Providers
Files
Resx
Mediator
Settings.settings
CBR.vssscc
CBR.csproj.vspscc
Devices.xlsx
Fluent.dll
ProgrammDiagram.cd
Languages
flag_france.png
flag_great_britain.png
Settings.settings
disk.png
file.png
folder.png
pin_no.png
pin_yes.png
sort_alpha.png
sort_category.png
view_details.png
view_thumb.png
book.png
book_add.png
book_close.png
book_convert.png
book_delete.png
book_edit.png
book_new.png
book_open.png
book_protect.png
book_read.png
book_remove.png
book_save.png
book_test.png
book_type_epub.png
book_type_none.png
book_type_rar.png
book_type_xps.png
book_type_zip.png
delete.png
device_refresh.png
device_sync.png
device_view.png
exit.png
fit_height.png
fit_width.png
forbidden.png
full_screen.png
help.png
info.png
is_read.png
library_close.png
library_new.png
library_open.png
library_view.png
localize.png
localize_new.png
localize_select.png
lock.png
open_folder.png
page_clear_mark.png
page_first.png
page_goto_mark.png
page_last.png
page_mark.png
page_next.png
page_previous.png
page_test.png
picture_order.png
picture_time.png
picture_zone.png
push_pin.png
read.png
refresh.png
resfresh.png
save.png
save_as.png
search.png
tools.png
book.ico
phone_horizontal.png
search.png
themes
Extended
Menus
Others
Explorer
Others
c__users_sean.office_desktop_holding_ground_cbr.zip
CBR.Core.dll
CBR.Core.pdb
CBR.exe
CBR.pdb
CBR.vshost.exe
7z.dll
cbl.ico
cbrz.ico
epub.ico
pdf.ico
rar.ico
Fluent.dll
itextsharp.dll
Languages
flag_france.png
flag_great_britain.png
Microsoft.Expression.Drawing.dll
Microsoft.Expression.Interactions.dll
SevenZipSharp.dll
System.Windows.Interactivity.dll
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CBR.Core.Models;
using CBR.Core.Helpers;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.Windows;
using System.Windows.Threading;
using System.Threading;
using System.Windows.Media.Imaging;
using SevenZip;
using CBR.Core.Files;
using System.Text.RegularExpressions;

namespace CBR.Core.Services
{
	public class BookService : BookServiceBase
	{
		override internal void LoadCoverThread(object param)
		{
			SevenZipExtractor temp = null;
			Book bk = param as Book;

			try
			{
				temp = ZipHelper.Instance.GetExtractor(bk.FilePath);
				bk.Size = temp.PackedSize / 1024 / 1024;
				bk.PageCount = temp.ArchiveFileNames.Count;

				foreach (ArchiveFileInfo fil in temp.ArchiveFileData)
				{
                    if (!fil.IsDirectory && FileService.Instance.ImageExtension.Contains(Path.GetExtension(fil.FileName).ToUpper()))
					{
                        using (MemoryStream stream = new MemoryStream())
                        {
                            temp.ExtractFile(fil.FileName, stream);

                            using (MemoryStream stream2 = new MemoryStream())
                            {
                                stream.WriteTo(stream2);
                                stream.Flush();
                                stream.Close();
                                stream2.Position = 0;

                                Application.Current.Dispatcher.Invoke(DispatcherPriority.Normal, (ThreadStart)delegate
                                {
                                    BitmapImage myImage = new BitmapImage();
                                    myImage.BeginInit();
                                    myImage.StreamSource = stream2;
                                    myImage.CacheOption = BitmapCacheOption.OnLoad;
                                    myImage.DecodePixelWidth = 70;
                                    myImage.EndInit();

                                    bk.Cover = myImage;
                                });

                                stream2.Flush();
                                stream2.Close();
                            }
                        }
						return;
					}
				}
			}
			catch (Exception err)
			{
                ExceptionHelper.Manage("BookService:LoadCoverThread", err);
			}
			finally
			{
                ZipHelper.Instance.ReleaseExtractor(temp);
			}
		}

        private int CheckFileNames(string fileName)
        {
            Regex MyRegex = new Regex("\\d+",
    RegexOptions.IgnoreCase
    | RegexOptions.Multiline
    | RegexOptions.CultureInvariant
    | RegexOptions.IgnorePatternWhitespace
    | RegexOptions.Compiled
    );

                FileInfo fi = new FileInfo(fileName);
                MatchCollection ms = MyRegex.Matches(fi.Name);
                Match m = ms[ms.Count - 1];
                return Convert.ToInt32(m.Value);
        }

		override public object LoadBook(Book bk)
		{
			SevenZipExtractor temp = null;
			try
			{
                base.LoadBook(bk);

                temp = ZipHelper.Instance.GetExtractor(bk.FilePath);
                bk.Size = temp.PackedSize / 1024 / 1024;
                bk.PageCount = temp.ArchiveFileNames.Count;

				foreach (ArchiveFileInfo fil in temp.ArchiveFileData)
				{
					if (!fil.IsDirectory)
					{
						if (FileService.Instance.ImageExtension.Contains(Path.GetExtension(fil.FileName).ToUpper()))
						{
							Page item = new Page(bk, fil.FileName, bk.Pages.Count);
                            item.Index = CheckFileNames(fil.FileName);
							bk.Pages.Add(item);
						}
					}
				}

                bk.Pages = bk.Pages.OrderBy(p => p.Index).ToList<Page>();

                foreach (ArchiveFileInfo fil in temp.ArchiveFileData)
				{
					if (!fil.IsDirectory && fil.FileName.Contains(".dynamics.xml"))
					{
                        Page pg = bk.Pages.Find(p => p.FileName == fil.FileName.Replace(".dynamics.xml", ""));
                        if (pg != null)
                        {
                            MemoryStream stream = new MemoryStream();
                            temp.ExtractFile(fil.FileName, stream);

                            MemoryStream stream2 = new MemoryStream();
                            stream.WriteTo(stream2);
                            stream.Flush();
                            stream.Close();
                            stream2.Position = 0;

                            pg.Frames = (List<Zone>)XmlHelper.Deserialize(stream2, typeof(List<Zone>));

                            stream2.Close();

                            if (pg.Frames == null) pg.Frames = new List<Zone>();
                        }
					}
				}
			}
			catch (Exception err)
			{
                ExceptionHelper.Manage("BookService:LoadBook", err);
			}
			finally
			{
                ZipHelper.Instance.ReleaseExtractor(temp);
			}
			return bk.Pages[0];
		}

        #region -----------------BOOK MANAGEMENT-----------------

        override public void EditBook(Book bk)
		{
			SevenZipExtractor temp = null;
			try
			{
                temp = ZipHelper.Instance.GetExtractor(bk.FilePath);

				foreach (ArchiveFileInfo fil in temp.ArchiveFileData)
				{
					if (!fil.IsDirectory)
					{
						if (fil.FileName.Contains(".dynamics.xml"))
						{
							Page item = new Page(bk, fil.FileName, bk.Pages.Count);
							bk.Pages.Add(item);
						}
					}
				}
			}
			catch (Exception err)
			{
                ExceptionHelper.Manage("BookService:EditBook", err);
			}
			finally
			{
                ZipHelper.Instance.ReleaseExtractor(temp);
			}
		}

        override public Book SaveBook(Book bk)
        {
            try
            {
                //first time we save as dynamic book
                if (IsDynamic(bk) && Path.GetExtension(bk.FilePath) != ".dcb")
                {
                    string newFile = FirstSaveDynamicBook(bk);
                    UnloadBook(bk);
                    return CreateBook(newFile);
                }
                else //only update the frame files
                {
                    UpdateDynamicBook(bk);
                }
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("BookService:SaveBook", err);
            }
            return null;
        }

        internal string FirstSaveDynamicBook(Book bk)
        {
            try
            {
                // create a temp folder
                string tempFolder = Path.Combine(DirectoryHelper.ApplicationPath, Path.GetFileNameWithoutExtension(bk.FilePath));
                DirectoryHelper.Check(tempFolder);

                //extract the book content
                ExtractBook(bk, tempFolder);

                //serialize all frames even empty to create the files in the zip
                foreach (Page pg in bk.Pages)
                {
                    XmlHelper.Serialize(Path.Combine(tempFolder, pg.FileName + ".dynamics.xml"), pg.Frames);
                }

                // create a new file by compressing all temp folder content
                string newComic = bk.FilePath.Replace(Path.GetExtension(bk.FilePath), ".dcb");

                SevenZip.SevenZipCompressor cp = new SevenZip.SevenZipCompressor();
                cp.ArchiveFormat = SevenZip.OutArchiveFormat.Zip;

                string[] outputFiles = new DirectoryInfo(tempFolder).GetFiles("*.*").Select(p => p.FullName).ToArray();

                using (FileStream fs = new FileStream(newComic, FileMode.Create))
                {
                    cp.CompressFiles(fs, outputFiles);
                }

                //delete the temp folder
                Directory.Delete(tempFolder, true);

                return newComic;
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("BookService:FirstSaveDynamicBook", err);
            }
            return null;
        }

        internal void UpdateDynamicBook(Book bk)
        {
            try
            {
                
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("BookService:UpdateDynamicBook", err);
            }
        }

        internal Dictionary<int, string> GetBookContentList(Book bk)
        {
            SevenZipExtractor temp = null;
            Dictionary<int, string> content = new Dictionary<int, string>();
            try
            {
                temp = ZipHelper.Instance.GetExtractor(bk.FilePath);

                foreach (ArchiveFileInfo fil in temp.ArchiveFileData)
                {
                    if (!fil.IsDirectory)
                    {
                        content.Add(content.Count, fil.FileName);
                    }
                }
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("BookService:GetBookContentList", err);
            }
            finally
            {
                ZipHelper.Instance.ReleaseExtractor(temp);
            }

            return content;
        }

        internal void ExtractBook(Book bk, string outputFolder)
        {
            SevenZipExtractor temp = null;
            try
            {
                temp = ZipHelper.Instance.GetExtractor(bk.FilePath);
                temp.PreserveDirectoryStructure = false;
                temp.ExtractArchive(outputFolder);
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("BookService:ExtractBook", err);
            }
            finally
            {
                ZipHelper.Instance.ReleaseExtractor(temp);
            }
        }

       
		#endregion

		public BitmapImage GetImageFromStream(string zipFilePath, string fileName)
		{
            SevenZipExtractor temp = null;
            BitmapImage result = null;
			try
			{
                temp = ZipHelper.Instance.GetExtractor(zipFilePath);

			    MemoryStream stream = new MemoryStream();
                temp.ExtractFile(fileName, stream);

			    result = StreamToImage.GetImageFromStreamBug(stream, 0);
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("BookService:GetImageFromStream", err);
            }
            finally
            {
                ZipHelper.Instance.ReleaseExtractor(temp);
            }
            return result;
        }

		#region -----------------BOOKMARK-----------------

		override public void SetMark(Book bk, Page pg)
		{
            if (bk != null && pg != null)
		    	bk.Bookmark = pg.FilePath;
		}

        override public Page GotoMark(Book bk)
		{
            if (bk != null)
            {
                if (!string.IsNullOrEmpty(bk.Bookmark))
                {
                    foreach (Page pg in bk.Pages)
                    {
                        if (pg.FilePath == bk.Bookmark)
                        {
                            return pg;
                        }
                    }
                }
            }
            
            return null;
		}

		#endregion

		#region -----------------page navigation management-----------------

		override public Page GotoPage(Book bk, Page currentPage, int step)
		{
            Page result = base.GotoPage( bk, currentPage, step );

			if (step == 1)
			{
                Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.Background, (ThreadStart)delegate
                {
                    PreparePageCache(result);
                });
            }

            return result;
		}

		public bool CheckPageRange(Book bk, Page currentPage, int step)
		{
			int pos = 0;

			if (currentPage != null)
				pos = bk.Pages.IndexOf(currentPage);

			if (step == -1)
			{
				return (pos == 0) ? false : true;
			}
			else
			{
				return (pos >= bk.Pages.Count - 1) ? false : true;
			}
		}

        public void GotoFrame(Book bk, ref Page currentPage, ref Zone currentFrame, int step)
        {
            currentFrame = GotoFrame(currentPage, currentFrame, step);

            //we reach the min or max, change the page
            if (currentFrame == null)
                currentPage = GotoPage(bk, currentPage, step);

            GotoFrame(currentPage, currentFrame, step);
        }

        internal Zone GotoFrame(Page currentPage, Zone currentFrame, int step)
        {
            //if no frames, return a page frame
            if (currentPage.Frames.Count <= 0)
            {
                if (currentFrame == null)
                    return new Zone() { Duration = 15, OrderNum = 0, X = 0, Y = 0, Type = FrameType.Page };
                else
                    return null;
            }

            //search current frame position
            int posFrame = 0;
            if (currentFrame != null)
                posFrame = currentPage.Frames.IndexOf(currentFrame);

            //we go back, manage the min
            if (step == -1)
            {
                return (posFrame == 0) ? null : currentPage.Frames[posFrame - 1];
            }
            else //we go forward, manage the max
            {
                return (posFrame >= currentPage.Frames.Count - 1) ? null : currentPage.Frames[posFrame + 1];
            }
        }

		#endregion

        override public long ManageCache(Book bk)
		{
            int counter = bk.Pages.Where(p => p.ImageExist == true).Count();

            //select and delete if more than cache count
            IEnumerable<Page> filter = bk.Pages
                        .Where(p => p.ImageExist == true)
                        .OrderBy(p => p.Index).Take(counter - WorkspaceService.Instance.Settings.ImageCacheCount);

            foreach (Page item in filter)
                item.Image = null;

            //select and delete if over cache duration
            filter = bk.Pages
                        .Where(p => p.ImageExist == true &&
                                p.ImageLastAcces < DateTime.Now.AddMinutes(-WorkspaceService.Instance.Settings.ImageCacheDuration))
                        .OrderBy(p => p.Index);

            foreach (Page item in filter)
                item.Image = null;

            //return total size in cache
			return bk.Pages.Where(p => p.ImageExist == true).Sum(f => f.Image.StreamSource.Length) / 1024 / 1024;
		}

        internal void PreparePageCache(object threadParam)
        {
            Page currentPage = threadParam as Page;

            if (currentPage != null)
            {
                //load the 3 next pages after current page
                BitmapImage tmpImage = null;

                Page tmpPage = GetNextPage(currentPage);
                if (tmpPage != null) tmpImage = tmpPage.Image;

                tmpPage = GetNextPage(tmpPage);
                if (tmpPage != null) tmpImage = tmpPage.Image;

                tmpPage = GetNextPage(tmpPage);
                if (tmpPage != null) tmpImage = tmpPage.Image;
            }
        }

        internal Page GetNextPage(Page currentPage)
        {
            if (currentPage != null)
            {
                Book parent = currentPage.Parent;

                if (parent != null)
                {
                    int next = parent.Pages.IndexOf(currentPage);
                    if (next >= parent.Pages.Count - 1)
                        return null;
                    else
                    {
                        next = next + 1;
                        return parent.Pages[next];
                    }
                }
                else return null;
            }
            else return null;
        }
	}
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The GNU General Public License (GPLv3)

About the Author

Guillaume Waser
Architect A.C.S.
France France
No Biography provided

| Advertise | Privacy | Mobile
Web02 | 2.8.140721.1 | Last Updated 22 Oct 2012
Article Copyright 2011 by Guillaume Waser
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid