Click here to Skip to main content
15,888,610 members
Articles / Desktop Programming / WPF

C.B.R.

Rate me:
Please Sign up or sign in to vote.
4.96/5 (52 votes)
22 Oct 2012GPL329 min read 124.5K   1.8K   132  
Comic and electronic publication reader with library management, extended file conversion, and devices support.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows;
using System.Windows.Input;
using CBR.Components;
using CBR.Core.Files;
using CBR.Core.Helpers;
using CBR.Core.Models;
using CBR.Core.Services;
using System.ComponentModel;
using System.Reflection;

namespace CBR.ViewModels
{
	public partial class MainViewModel : ViewModelBase
	{
		#region ----------------CONSTRUCTOR----------------

		public MainViewModel()
		{
			//register to the mediator for messages
            Mediator.Instance.Register(
                (Object o) =>
                {
                    CatalogData = (Catalog)o;
                },
                ViewModelMessages.CatalogChanged);

            Mediator.Instance.Register(
                (Object o) =>
                {
                    List<string> lst = o as List<string>;
                    foreach( string file in lst )
                        AddBookFileCommand.Execute(file);
                }, 
                ViewModelMessages.CatalogRefresh);

            Mediator.Instance.Register(
                (Object o) =>
                {
                    ExecuteDistantCommand( o as CommandContext );
                },
                ViewModelMessages.ExplorerContextCommand);

            BackStageIsOpen = false;
		}

		#endregion

		#region ----------------PROPERTIES----------------

        public string Title
        {
            get
            {
                if (CatalogData == null) return "CRB";
                else
                    if (CurrentBookViewModel == null) return "CBR : " + CatalogData.CatalogFilePath;
                    else return "CBR : " + CurrentBookViewModel.BookData.FilePath;
            }
        }

        private BookViewModelBase _currentBookViewModel = null;
        public BookViewModelBase CurrentBookViewModel
        {
            get { return _currentBookViewModel; }
            set
            {
                if (_currentBookViewModel != value)
                {
                    _currentBookViewModel = value;
                    RaisePropertyChanged("CurrentBookViewModel");
                    RaisePropertyChanged("Title");
                }
            }
        }

		public bool IsInEditMode
		{
			get { if (CurrentBookViewModel != null) return CurrentBookViewModel.IsInEditMode; else return false; }
			set
			{
				if (CurrentBookViewModel.IsInEditMode != value)
				{
					CurrentBookViewModel.IsInEditMode = value;
					RaisePropertyChanged("IsInEditMode");
				}
			}
		}

        private bool _backStageIsOpen = false;
        public bool BackStageIsOpen
        {
            get { return _backStageIsOpen; }
            set
            {
                if (_backStageIsOpen != value)
                {
                    _backStageIsOpen = value;
                    RaisePropertyChanged("BackStageIsOpen");
                }
            }
        }


        private int _backStageIndex = -1;
        public int BackStageIndex
        {
            get { return _backStageIndex; }
            set
            {
                if (_backStageIndex != value)
                {
                    _backStageIndex = value;
                    RaisePropertyChanged("BackStageIndex");
                }
            }
        }
        
        private Catalog CatalogData { get; set; }

		#endregion

		#region ---------------- SYSTEM ----------------

        #region exit command
        private ICommand sysExitCommand;
		public ICommand SysExitCommand
		{
			get
			{
                if (sysExitCommand == null)
                    sysExitCommand = new DelegateCommand(
						delegate() { CloseCatalog(); Application.Current.MainWindow.Close(); },
						delegate()
						{
							if (Application.Current != null && Application.Current.MainWindow != null)
								return true;
							return false;
						});
                return sysExitCommand;
			}
		}
        #endregion

        #region view command
        private ICommand sysExplorerViewCommand;
        public ICommand SysExplorerViewCommand
        {
            get
            {
                if (sysExplorerViewCommand == null)
                    sysExplorerViewCommand = new DelegateCommand<string>(
                        delegate(string param) { Mediator.Instance.NotifyColleagues(ViewModelMessages.ExplorerView, param); },
                        delegate(string param)
                        {
                            return CatalogData != null;
                        });
                return sysExplorerViewCommand;
            }
        }
        #endregion

        #endregion

        #region ----------------CATALOG----------------

        #region new catalog command
        private ICommand catalogNewCommand;
        public ICommand CatalogNewCommand
        {
            get
            {
                if (catalogNewCommand == null)
                    catalogNewCommand = new DelegateCommand(NewCatalog, delegate() { return true; });
                return catalogNewCommand;
            }
        }

        void NewCatalog()
        {
            try
            {
                // check if opened and not save before

                //create a new one
                using (System.Windows.Forms.SaveFileDialog browser = new System.Windows.Forms.SaveFileDialog())
                {
                    browser.AddExtension = true;
                    browser.Filter = FileExtensionManager.Instance.CatalogFilterAll;
                    browser.DefaultExt = FileExtensionManager.Instance.CatalogFilterDefaultExtension;
                    browser.FilterIndex = FileExtensionManager.Instance.CatalogFilterDefaultIndex;

                    if (browser.ShowDialog(new Wpf32Window()) == System.Windows.Forms.DialogResult.OK)
                    {
                        Mediator.Instance.NotifyColleagues(ViewModelMessages.CatalogChanged, new Catalog(browser.FileName));
                    }
                }
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("MainViewModel:OpenCatalog", err);
            }
        }
        #endregion

		#region open catalog command
		private ICommand catalogOpenCommand;
		public ICommand CatalogOpenCommand
		{
			get
			{
                if (catalogOpenCommand == null)
                    catalogOpenCommand = new DelegateCommand(OpenCatalog, delegate() { return true; });
                return catalogOpenCommand;
			}
		}

		void OpenCatalog()
		{
			try
			{
				using (System.Windows.Forms.OpenFileDialog browser = new System.Windows.Forms.OpenFileDialog())
				{
                    browser.Filter= FileExtensionManager.Instance.CatalogFilterAll;
                    browser.FilterIndex = FileExtensionManager.Instance.CatalogFilterDefaultIndex;

                    if (browser.ShowDialog(new Wpf32Window()) == System.Windows.Forms.DialogResult.OK)
					{
                        OpenFileCatalog(browser.FileName);
					}
				}
			}
			catch (Exception err)
			{
				ExceptionHelper.Manage("MainViewModel:OpenCatalog", err);
			}
		}
		#endregion

        #region open file catalog command
        private ICommand catalogOpenFileCommand;
        public ICommand CatalogOpenFileCommand
        {
            get
            {
                if (catalogOpenFileCommand == null)
                    catalogOpenFileCommand = new DelegateCommand<string>(OpenFileCatalog, delegate(string param) { return true; });
                return catalogOpenFileCommand;
            }
        }

        void OpenFileCatalog(string param)
        {
            try
            {
                if( File.Exists( param ) )
                {
                    Mediator.Instance.NotifyColleagues(ViewModelMessages.CatalogChanged, CatalogService.Instance.Open(param));
                }
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("MainViewModel:OpenFileCatalog", err);
            }
        }
        #endregion

		#region save catalog command
		private ICommand catalogSaveCommand;
		public ICommand CatalogSaveCommand
		{
			get
			{
                if (catalogSaveCommand == null)
                    catalogSaveCommand = new DelegateCommand(SaveCatalog, delegate() { return (CatalogData != null); });
                return catalogSaveCommand;
			}
		}

		void SaveCatalog()
		{
            CatalogService.Instance.Save(CatalogData);
		}
		#endregion

		#region save as catalog command
		private ICommand catalogSaveAsCommand;
		public ICommand CatalogSaveAsCommand
		{
			get
			{
                if (catalogSaveAsCommand == null)
                    catalogSaveAsCommand = new DelegateCommand(SaveAsCatalog, delegate() { return (CatalogData != null); });
                return catalogSaveAsCommand;
			}
		}

		void SaveAsCatalog()
		{
			try
			{
				using (System.Windows.Forms.OpenFileDialog browser = new System.Windows.Forms.OpenFileDialog())
				{
                    browser.Filter = FileExtensionManager.Instance.CatalogFilterAll;
                    browser.FilterIndex = FileExtensionManager.Instance.CatalogFilterDefaultIndex;
                    browser.DefaultExt = FileExtensionManager.Instance.CatalogFilterDefaultExtension;

                    if (browser.ShowDialog(new Wpf32Window()) == System.Windows.Forms.DialogResult.OK)
					{
                        CatalogService.Instance.SaveAs(CatalogData, browser.FileName);
					}
				}
			}
			catch (Exception err)
			{
				ExceptionHelper.Manage("MainViewModel:SaveAsCatalog", err);
			}
		}
		#endregion

		#region refresh catalog command
		private ICommand catalogRefreshCommand;
        public ICommand CatalogRefreshCommand
		{
			get
			{
                if (catalogRefreshCommand == null)
                    catalogRefreshCommand = new DelegateCommand(RefreshCatalog,
						delegate()
						{
                            return (CatalogData != null);
						});
                return catalogRefreshCommand;
			}
		}

		void RefreshCatalog()
		{
            CatalogService.Instance.Refresh(CatalogData);
		}
		#endregion

		#region close catalog command
		private ICommand catalogCloseCommand;
		public ICommand CatalogCloseCommand
		{
			get
			{
                if (catalogCloseCommand == null)
                    catalogCloseCommand = new DelegateCommand(CloseCatalog,
						delegate()
						{
                            return CatalogData != null;
						});
                return catalogCloseCommand;
			}
		}

		void CloseCatalog()
		{
            if (CatalogData != null)
			{
                if (CatalogService.Instance.IsDirty(CatalogData))
				{
					if( MessageBox.Show( "Save the catalog and book changes ?", "Warning", MessageBoxButton.YesNo ) == MessageBoxResult.Yes )
                        CatalogService.Instance.Save(CatalogData);
				}

                Mediator.Instance.NotifyColleagues(ViewModelMessages.CatalogChanged, null);
			}
		}
		#endregion
		
		#endregion

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

        #region open command
        private ICommand bookOpenCommand;
        public ICommand BookOpenCommand
        {
            get
            {
                if (bookOpenCommand == null)
                    bookOpenCommand = new DelegateCommand(OpenBook, delegate() { return true; });
                return bookOpenCommand;
            }
        }

        void OpenBook()
        {
            try
            {
                using (System.Windows.Forms.OpenFileDialog browser = new System.Windows.Forms.OpenFileDialog())
                {
                    browser.FilterIndex = FileExtensionManager.Instance.BookFilterDefaultIndex;
                    browser.Filter = FileExtensionManager.Instance.BookFilterAllEditable;

                    if (browser.ShowDialog(new Wpf32Window()) == System.Windows.Forms.DialogResult.OK)
                    {
                        OpenFileBook(browser.FileName);
                    }
                }
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("MainViewModel:OpenBook", err);
            }
        }
        #endregion

		#region open file command
		private ICommand bookOpenFileCommand;
        public ICommand BookOpenFileCommand
		{
			get
			{
                if (bookOpenFileCommand == null)
                    bookOpenFileCommand = new DelegateCommand<string>(OpenFileBook, delegate(string param) { return true; });
                return bookOpenFileCommand;
			}
		}

		void OpenFileBook(string param)
		{
			try
			{
                ReadBook( BookServiceFactory.Instance.GetService(param).CreateBook( param ) );
			}
			catch (Exception err)
			{
                ExceptionHelper.Manage("MainViewModel:OpenFileBook", err);
			}
		}
		#endregion

		#region read command
		private ICommand bookReadCommand;
		public ICommand BookReadCommand
		{
			get
			{
                if (bookReadCommand == null)
                    bookReadCommand = new DelegateCommand<Book>(ReadBook, delegate(Book bk) { return bk != null && !bk.IsSecured; });
                return bookReadCommand;
			}
		}

		void ReadBook(Book bookAsParam)
		{
			try
			{
				if (CurrentBookViewModel != null)
				    CurrentBookViewModel.Close();

                //to improve !
                if (FileExtensionManager.Instance.FindBookFilterByExt(Path.GetExtension(bookAsParam.FilePath)).Service == typeof(BookService))
                    CurrentBookViewModel = new BookViewModel(bookAsParam);
                else 
                    CurrentBookViewModel = new XpsBookViewModel(bookAsParam);
            }
			catch (Exception err)
			{
				ExceptionHelper.Manage("MainViewModel:OpenBook", err);
			}
		}
		#endregion

        #region close command
        private ICommand bookCloseCommand;
        public ICommand BookCloseCommand
        {
            get
            {
                if (bookCloseCommand == null)
                    bookCloseCommand = new DelegateCommand(Close, delegate() { return CurrentBookViewModel != null; });
                return bookCloseCommand;
            }
        }

        public void Close()
        {
            CurrentBookViewModel.Close();
            CurrentBookViewModel = null;
        }

        #endregion

		#region edit command
		private ICommand bookEditCommand;
		public ICommand BookEditCommand
		{
			get
			{
                if (bookEditCommand == null)
                    bookEditCommand = new DelegateCommand<Book>(EditBook, CanEditBook);
                return bookEditCommand;
			}
		}

        bool CanEditBook(Book bk)
        {
            try
            {
                if (bk != null || (CurrentBookViewModel != null && CurrentBookViewModel.BookData != null && !CurrentBookViewModel.IsInEditMode ))
                    return true;
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("MainViewModel:CanEditBook", err);
            }
            return false;
        }

        void EditBook(Book bk)
		{
			try
			{
				IsInEditMode = !IsInEditMode;

				if (CurrentBookViewModel != null)
					CurrentBookViewModel.IsInEditMode = IsInEditMode;
			}
			catch (Exception err)
			{
				ExceptionHelper.Manage("MainViewModel:EditBook", err);
			}
		}
		#endregion

		#region delete command
		private ICommand bookDeleteCommand;
        public ICommand BookDeleteCommand
		{
			get
			{
                if (bookDeleteCommand == null)
                    bookDeleteCommand = new DelegateCommand<Book>(DeleteBook, delegate(Book bk) { return bk != null; });
                return bookDeleteCommand;
			}
		}

        void DeleteBook(Book bk)
        {
            try
            {
                //message de confirmation
                if (MessageBox.Show("Are you sure ?", "Warning", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
                {
                    BookServiceFactory.Instance.GetService(bk).Delete(bk);
                    CatalogData.Books.Remove(bk);
                }
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("MainViewModel:EditBook", err);
            }
        }
		#endregion

        #region protect command
        private ICommand bookProtectCommand;
        public ICommand BookProtectCommand
        {
            get
            {
                if (bookProtectCommand == null)
                    bookProtectCommand = new DelegateCommand<Book>(ProtectBook, delegate(Book bk) { return bk != null; });
                return bookProtectCommand;
            }
        }

        void ProtectBook(Book bk)
        {
            try
            {
                PasswordDialog dlg = new PasswordDialog();
                dlg.Owner = Application.Current.MainWindow;
                dlg.ShowDialog();
                if (dlg.DialogResult == true)
                    BookServiceFactory.Instance.GetService(bk).Protect(bk, !bk.IsSecured, dlg.PassBox.Password);
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("MainViewModel:EditBook", err);
            }
        }
        #endregion

        #region mark as read command
        private ICommand bookMarkAsReadCommand;
        public ICommand BookMarkAsReadCommand
        {
            get
            {
                if (bookMarkAsReadCommand == null)
                    bookMarkAsReadCommand = new DelegateCommand<Book>(MarkAsRead, delegate(Book bk) { return bk != null; });
                return bookMarkAsReadCommand;
            }
        }

        void MarkAsRead(Book bk)
        {
            try
            {
                bk.IsRead = !bk.IsRead;
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("MainViewModel:MarkAsRead", err);
            }
        }
        #endregion

        #region add book command
        private ICommand bookAddCommand;
        public ICommand BookAddCommand
        {
            get
            {
                if (bookAddCommand == null)
                    bookAddCommand = new DelegateCommand<string>(AddBook, delegate(string param) { return CatalogData != null; });
                return bookAddCommand;
            }
        }

        void AddBook(string param)
        {
            try
            {
                //add one file to the library
                if (param == "One")
                {
                    using (System.Windows.Forms.OpenFileDialog browser = new System.Windows.Forms.OpenFileDialog())
                    {
                        browser.AddExtension = true;
                        browser.Filter = FileExtensionManager.Instance.BookFilterAllEditable;
                        browser.FilterIndex = FileExtensionManager.Instance.BookFilterDefaultIndex;

                        if (browser.ShowDialog(new Wpf32Window()) == System.Windows.Forms.DialogResult.OK)
                        {
                            CatalogService.Instance.AddBook(CatalogData, browser.FileName);
                        }
                    }
                }
                else // or all founded in a folder
                {
                    if (!string.IsNullOrEmpty(CatalogData.BookFolder))
                    {
                        if (MessageBox.Show("Your book folder is allready defined. Do you want to replace it ? Refreshing will work only with the new one.", "Warning", MessageBoxButton.OKCancel) == MessageBoxResult.Cancel)
                            return;
                    }

                    using (System.Windows.Forms.FolderBrowserDialog browser = new System.Windows.Forms.FolderBrowserDialog())
                    {
                        if (browser.ShowDialog(new Wpf32Window()) == System.Windows.Forms.DialogResult.OK)
                        {
                            CatalogData.BookFolder = browser.SelectedPath;
                            CatalogService.Instance.Refresh(CatalogData);
                        }
                    }

                }
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("MainViewModel:AddBook", err);
            }
        }

        private ICommand addBookFileCommand;
        public ICommand AddBookFileCommand
        {
            get
            {
                if (addBookFileCommand == null)
                    addBookFileCommand = new DelegateCommand<string>(AddFileBook, delegate(string param) { return CatalogData != null; });
                return addBookFileCommand;
            }
        }

        void AddFileBook(string fileBook)
        {
            try
            {
                CatalogService.Instance.AddBook(CatalogData, fileBook);
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("MainViewModel:AddFileBook", err);
            }
        }

        #endregion

        #region property command
        private ICommand bookPropertyCommand;
        public ICommand BookPropertyCommand
        {
            get
            {
                if (bookPropertyCommand == null)
                    bookPropertyCommand = new DelegateCommand<Book>(DisplayProperty, delegate(Book bk) { return bk != null; });
                return bookPropertyCommand;
            }
        }

        void DisplayProperty(Book bk)
        {
            try
            {
                BackStageIndex = 4;
                BackStageIsOpen = true;
            }
            catch (Exception err)
            {
                ExceptionHelper.Manage("MainViewModel:DisplayProperty", err);
            }
        }
        #endregion

		#endregion

        internal void ExecuteDistantCommand(CommandContext context)
        {
            if (context != null)
            {
                new ReflectionHelper().ExecuteICommand( this, context.CommandName, context.CommandParameter );
            }
        }
	}
}

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)


Written By
Architect
France France
WPF and MVVM fan, I practice C # in all its forms from the beginning of the NET Framework without mentioning C ++ / MFC and other software packages such as databases, ASP, WCF, Web & Windows services, Application, and now Core and UWP.
In my wasted hours, I am guilty of having fathered C.B.R. and its cousins C.B.R. for WinRT and UWP on the Windows store.
But apart from that, I am a great handyman ... the house, a rocket stove to heat the jacuzzi and the last one: a wood oven for pizza, bread, and everything that goes inside

https://guillaumewaser.wordpress.com/
https://fouretcompagnie.wordpress.com/

Comments and Discussions