PageRenderTime 31ms CodeModel.GetById 11ms app.highlight 15ms RepoModel.GetById 1ms app.codeStats 0ms

/CBR/CBR/ViewModels/MainViewModel.cs

#
C# | 691 lines | 543 code | 86 blank | 62 comment | 88 complexity | e3e9fb51c80cee89e39eca4a51f985e2 MD5 | raw file
  1using System;
  2using System.Collections.Generic;
  3using System.IO;
  4using System.Linq;
  5using System.Windows;
  6using System.Windows.Input;
  7using CBR.Components;
  8using CBR.Core.Files;
  9using CBR.Core.Helpers;
 10using CBR.Core.Models;
 11using CBR.Core.Services;
 12using System.ComponentModel;
 13using System.Reflection;
 14using System.Collections.ObjectModel;
 15using System.Windows.Data;
 16using System.Collections.Specialized;
 17using CBR.Components.Controls;
 18using System.Globalization;
 19using CBR.Core.Helpers.Localization;
 20
 21namespace CBR.ViewModels
 22{
 23	public partial class MainViewModel : ViewModelBase
 24	{
 25		#region ----------------CONSTRUCTOR----------------
 26
 27		public MainViewModel(string param)
 28		{
 29			//register to the mediator for messages
 30			Mediator.Instance.RegisterHandler<Catalog>(ViewModelMessages.CatalogChanged,
 31				(Catalog o) =>
 32                {
 33                    Data = o;
 34                } );
 35
 36            Mediator.Instance.RegisterHandler(ViewModelMessages.CatalogRefresh,
 37                (Object o) =>
 38                {
 39                    List<string> lst = o as List<string>;
 40                    foreach( string file in lst )
 41                        AddBookFileCommand.Execute(file);
 42                } );
 43
 44			Mediator.Instance.RegisterHandler<CommandContext>(ViewModelMessages.ContextCommand,
 45				(CommandContext o) =>
 46                {
 47                    ExecuteDistantCommand( o );
 48                } );
 49
 50			Mediator.Instance.RegisterHandler<BookViewModelBase>(ViewModelMessages.SwapTwoPageView,
 51				(BookViewModelBase o) =>
 52				{
 53					SwapTwoPageMode(o);
 54				});
 55
 56            BackStageIsOpen = false;
 57
 58            ViewModels.Add(new HomeViewModel());
 59
 60            if (!string.IsNullOrEmpty(param))
 61                HandleStartingDocument(param);
 62		}
 63
 64		#endregion
 65
 66		#region ----------------PROPERTIES----------------
 67
 68        public string Title
 69        {
 70            get
 71            {
 72                // no catalog
 73                if (Data == null)
 74                    return "CRB";
 75                
 76                // no open book
 77                if (BookViewModel == null)
 78                    return "CBR : " + Data.CatalogFilePath;
 79                else
 80                    return "CBR : " + BookViewModel.Data != null  ? BookViewModel.Data.FilePath : string.Empty;
 81            }
 82        }
 83
 84        public ObservableCollection<LanguageMenuItemViewModel> Languages
 85        {
 86            get
 87            {
 88                ObservableCollection<LanguageMenuItemViewModel> result = new ObservableCollection<LanguageMenuItemViewModel>();
 89                
 90                foreach( CultureItem info in CultureManager.Instance.GetAvailableCultures() )
 91                    result.Add( new LanguageMenuItemViewModel(info) );
 92                
 93                return result;
 94            }
 95        }
 96
 97        //private BookViewModelBase _currentBookViewModel = null;
 98        //public BookViewModelBase CurrentBookViewModel
 99        //{
100        //    get { return _currentBookViewModel; }
101        //    set
102        //    {
103        //        if (_currentBookViewModel != value)
104        //        {
105        //            _currentBookViewModel = value;
106        //            RaisePropertyChanged("CurrentBookViewModel");
107        //            RaisePropertyChanged("Title");
108        //        }
109        //    }
110        //}
111
112
113		public bool IsInEditMode
114		{
115            get { if (BookViewModel != null) return BookViewModel.IsInEditMode; else return false; }
116			set
117			{
118                if (BookViewModel.IsInEditMode != value)
119				{
120                    BookViewModel.IsInEditMode = value;
121					RaisePropertyChanged("IsInEditMode");
122				}
123			}
124		}
125
126        private bool _backStageIsOpen = false;
127        public bool BackStageIsOpen
128        {
129            get { return _backStageIsOpen; }
130            set
131            {
132                if (_backStageIsOpen != value)
133                {
134                    _backStageIsOpen = value;
135                    RaisePropertyChanged("BackStageIsOpen");
136                }
137            }
138        }
139
140
141        private int _backStageIndex = -1;
142        public int BackStageIndex
143        {
144            get { return _backStageIndex; }
145            set
146            {
147                if (_backStageIndex != value)
148                {
149                    _backStageIndex = value;
150                    RaisePropertyChanged("BackStageIndex");
151                }
152            }
153        }
154
155        new public Catalog Data
156        {
157            get { return base.Data as Catalog; }
158            set { base.Data = value; }
159        }
160
161        private ObservableCollection<ViewModelBase> _viewModels = null;
162        public ObservableCollection<ViewModelBase> ViewModels
163        {
164            get
165            {
166                if (_viewModels == null)
167                {
168                    _viewModels = new ObservableCollection<ViewModelBase>();
169                    _viewModels.CollectionChanged += OnViewModelsChanged;
170                }
171                return _viewModels;
172            }
173            //set
174            //{
175            //    if (_viewModels != value)
176            //    {
177            //        _viewModels = value;
178            //        RaisePropertyChanged("ViewModels");
179            //        RaisePropertyChanged("BookViewModel");
180
181            //        RaisePropertyChanged("USBDeviceViewModel");
182            //        RaisePropertyChanged("HasUSBDevice");
183            //        RaisePropertyChanged("HasDevice");
184            //        RaisePropertyChanged("HasBook");
185            //    }
186            //}
187        }
188
189        void OnViewModelsChanged(object sender, NotifyCollectionChangedEventArgs e)
190        {
191            RaisePropertyChanged("ViewModels");
192            RaisePropertyChanged("BookViewModel");
193            RaisePropertyChanged("USBDeviceViewModel");
194
195            RaisePropertyChanged("HasUSBDevice");
196            RaisePropertyChanged("HasDevice");
197            RaisePropertyChanged("HasBook");
198
199			RaisePropertyChanged("IsFitModeWidth");
200			RaisePropertyChanged("IsFitModeHeight");
201			RaisePropertyChanged("IsFitModeNone");
202
203            RaisePropertyChanged("BookmarkCommand");
204            RaisePropertyChanged("GotoBookmarkCommand");
205            RaisePropertyChanged("ClearBookmarkCommand");
206
207            RaisePropertyChanged("FitModeCommand");
208            RaisePropertyChanged("BookGotoPageCommand");
209            RaisePropertyChanged("BookChangePageCommand");
210            RaisePropertyChanged("BookGotoLastPageCommand");
211			RaisePropertyChanged("TwoPageCommand");
212        }
213
214        /// <summary>
215        /// The one and only one in the view collection
216        /// </summary>
217        public BookViewModelBase BookViewModel
218        {
219            get
220            {
221                if (HasBook)
222                    return ViewModels.Where(p => p is BookViewModelBase).First() as BookViewModelBase;
223                else
224                    return null;
225            }
226            //set
227            //{
228            //    if (HasBook)
229            //        ViewModels.Remove(ViewModels.Where(p => p is BookViewModelBase).First());
230
231            //    if (value != null)
232            //    {
233            //        ViewModels.Add(value);
234            //        SetActiveView(value);
235
236            //        RaisePropertyChanged("BookViewModel");
237            //        RaisePropertyChanged("Title");
238            //        RaisePropertyChanged("HasBook");
239
240            //        RaisePropertyChanged("BookmarkCommand");
241            //        RaisePropertyChanged("GotoBookmarkCommand");
242            //        RaisePropertyChanged("ClearBookmarkCommand");
243
244            //        RaisePropertyChanged("FitModeCommand");
245            //        RaisePropertyChanged("BookGotoPageCommand");
246            //        RaisePropertyChanged("BookChangePageCommand");
247            //    }
248            //}
249        }
250
251        public bool HasBook
252        {
253            get
254            {
255				return ViewModels.Where(p => p is TwoPageViewModel || p is ComicViewModel || 
256					p is ePUBBookViewModel || p is XpsBookViewModel).Count() != 0;
257            }
258        }
259
260
261        public bool HasDevice
262        {
263            get
264            {
265                return ViewModels.Where(p => p is USBDeviceViewModel).Count() != 0;
266            }
267        }
268
269        public USBDeviceViewModel USBDeviceViewModel
270        {
271            get
272            {
273                if (ViewModels.Where(p => p is USBDeviceViewModel).Count() != 0)
274                    return ViewModels.Where(p => p is USBDeviceViewModel).First() as USBDeviceViewModel;
275                else
276                    return null;
277            }
278            //set
279            //{
280            //    if (ViewModels.Where(p => p is USBDeviceViewModel).Count() != 0)
281            //        ViewModels.Remove(ViewModels.Where(p => p is USBDeviceViewModel).First());
282
283            //    ViewModels.Add(value);
284
285            //    RaisePropertyChanged("USBDeviceViewModel");
286            //    RaisePropertyChanged("HasUSBDevice");
287            //}
288        }
289
290        public bool HasUSBDevice
291        {
292            get
293            {
294                return (USBDeviceViewModel != null);
295            }
296        }
297
298		#endregion
299
300		#region ---------------- SYSTEM ----------------
301
302        public void HandleStartingDocument(string param)
303        {
304            FileInfo fi = new FileInfo( param );
305            if( fi.Exists )
306            {
307                if (FileService.Instance.FindCatalogFilterByExt(fi.Extension) != null)
308                    this.OpenFileCatalog(param);
309
310                if (FileService.Instance.FindBookFilterByExt(fi.Extension) != null)
311                    this.OpenFileBook(param);
312            }
313        }
314
315        #region help command
316        private ICommand sysHelpCommand;
317        public ICommand SysHelpCommand
318        {
319            get
320            {
321                if (sysHelpCommand == null)
322                    sysHelpCommand = new DelegateCommand(
323                        delegate()
324                        {
325                            ProcessHelper.LaunchWebUri(new Uri(CBR.Properties.Settings.Default.HelpUrl));
326                        },
327                        delegate() { return true;}
328                        );
329                return sysHelpCommand;
330            }
331        }
332        #endregion
333
334        #region exit command
335        private ICommand sysExitCommand;
336		public ICommand SysExitCommand
337		{
338			get
339			{
340                if (sysExitCommand == null)
341                    sysExitCommand = new DelegateCommand(
342						delegate() { CloseCatalog(); Application.Current.MainWindow.Close(); },
343						delegate()
344						{
345							if (Application.Current != null && Application.Current.MainWindow != null)
346								return true;
347							return false;
348						});
349                return sysExitCommand;
350			}
351		}
352        #endregion
353
354        #region view command
355        private ICommand sysExplorerViewCommand;
356        public ICommand SysExplorerViewCommand
357        {
358            get
359            {
360                if (sysExplorerViewCommand == null)
361                    sysExplorerViewCommand = new DelegateCommand<string>(
362                        delegate(string param) { Mediator.Instance.NotifyColleagues(ViewModelMessages.ExplorerView, param); },
363                        delegate(string param)
364                        {
365                            return Data != null;
366                        });
367                return sysExplorerViewCommand;
368            }
369        }
370        #endregion
371
372        #region add usb device command
373        private ICommand sysDeviceAddCommand;
374        public ICommand SysDeviceAddCommand
375        {
376            get
377            {
378                if (sysDeviceAddCommand == null)
379                    sysDeviceAddCommand = new DelegateCommand<USBDiskInfo>( DeviceAdd, delegate(USBDiskInfo param) { return true; } );
380                return sysDeviceAddCommand;
381            }
382        }
383
384        void DeviceAdd( USBDiskInfo param )
385        {
386            try
387            {
388                if (this.USBDeviceViewModel == null)
389                    this.ViewModels.Add(new USBDeviceViewModel(param));
390                else
391                    Mediator.Instance.NotifyColleagues(ViewModelMessages.DeviceAdded, param);
392            }
393            catch (Exception err)
394            {
395                ExceptionHelper.Manage("MainViewModel:DeviceAdd", err);
396            }
397        }
398
399        #endregion
400
401        #region remove usb device command
402        private ICommand sysDeviceRemoveCommand;
403        public ICommand SysDeviceRemoveCommand
404        {
405            get
406            {
407                if (sysDeviceRemoveCommand == null)
408                    sysDeviceRemoveCommand = new DelegateCommand<USBDiskInfo>( DeviceRemove,
409                        delegate(USBDiskInfo param) { return this.USBDeviceViewModel != null; }
410                        );
411                return sysDeviceRemoveCommand;
412            }
413        }
414
415        void DeviceRemove(USBDiskInfo param)
416        {
417            try
418            {
419                if (this.USBDeviceViewModel != null)
420                    Mediator.Instance.NotifyColleagues(ViewModelMessages.DeviceRemoved, param);
421            }
422            catch (Exception err)
423            {
424                ExceptionHelper.Manage("MainViewModel:DeviceAdd", err);
425            }
426        }
427
428        #endregion
429
430        #endregion
431
432        #region ----------------CATALOG----------------
433
434        #region new catalog command
435        private ICommand catalogNewCommand;
436        public ICommand CatalogNewCommand
437        {
438            get
439            {
440                if (catalogNewCommand == null)
441                    catalogNewCommand = new DelegateCommand(NewCatalog, delegate() { return true; });
442                return catalogNewCommand;
443            }
444        }
445
446        void NewCatalog()
447        {
448            try
449            {
450                // check if opened and not save before
451
452                //create a new one
453                using (System.Windows.Forms.SaveFileDialog browser = new System.Windows.Forms.SaveFileDialog())
454                {
455                    browser.AddExtension = true;
456                    browser.Filter = FileService.Instance.CatalogFilterAll;
457                    browser.DefaultExt = FileService.Instance.CatalogFilterDefaultExtension;
458                    browser.FilterIndex = FileService.Instance.CatalogFilterDefaultIndex;
459
460                    if (browser.ShowDialog(new Wpf32Window()) == System.Windows.Forms.DialogResult.OK)
461                    {
462                        Mediator.Instance.NotifyColleagues(ViewModelMessages.CatalogChanged, new Catalog(browser.FileName));
463                    }
464                }
465            }
466            catch (Exception err)
467            {
468                ExceptionHelper.Manage("MainViewModel:OpenCatalog", err);
469            }
470        }
471        #endregion
472
473		#region open catalog command
474		private ICommand catalogOpenCommand;
475		public ICommand CatalogOpenCommand
476		{
477			get
478			{
479                if (catalogOpenCommand == null)
480                    catalogOpenCommand = new DelegateCommand(OpenCatalog, delegate() { return true; });
481                return catalogOpenCommand;
482			}
483		}
484
485		void OpenCatalog()
486		{
487			try
488			{
489				using (System.Windows.Forms.OpenFileDialog browser = new System.Windows.Forms.OpenFileDialog())
490				{
491                    browser.Filter= FileService.Instance.CatalogFilterAll;
492                    browser.FilterIndex = FileService.Instance.CatalogFilterDefaultIndex;
493
494                    if (browser.ShowDialog(new Wpf32Window()) == System.Windows.Forms.DialogResult.OK)
495					{
496                        OpenFileCatalog(browser.FileName);
497					}
498				}
499			}
500			catch (Exception err)
501			{
502				ExceptionHelper.Manage("MainViewModel:OpenCatalog", err);
503			}
504		}
505		#endregion
506
507        #region open file catalog command
508        private ICommand catalogOpenFileCommand;
509        public ICommand CatalogOpenFileCommand
510        {
511            get
512            {
513                if (catalogOpenFileCommand == null)
514                    catalogOpenFileCommand = new DelegateCommand<string>(OpenFileCatalog, delegate(string param) { return true; });
515                return catalogOpenFileCommand;
516            }
517        }
518
519        void OpenFileCatalog(string param)
520        {
521            try
522            {
523                if( File.Exists( param ) )
524                {
525                    Mediator.Instance.NotifyColleagues(ViewModelMessages.CatalogChanged, CatalogService.Instance.Open(param));
526                }
527            }
528            catch (Exception err)
529            {
530                ExceptionHelper.Manage("MainViewModel:OpenFileCatalog", err);
531            }
532        }
533        #endregion
534
535		#region save catalog command
536		private ICommand catalogSaveCommand;
537		public ICommand CatalogSaveCommand
538		{
539			get
540			{
541                if (catalogSaveCommand == null)
542                    catalogSaveCommand = new DelegateCommand(SaveCatalog, delegate() { return (Data != null); });
543                return catalogSaveCommand;
544			}
545		}
546
547		void SaveCatalog()
548		{
549            CatalogService.Instance.Save(Data);
550		}
551		#endregion
552
553		#region save as catalog command
554		private ICommand catalogSaveAsCommand;
555		public ICommand CatalogSaveAsCommand
556		{
557			get
558			{
559                if (catalogSaveAsCommand == null)
560                    catalogSaveAsCommand = new DelegateCommand(SaveAsCatalog, delegate() { return (Data != null); });
561                return catalogSaveAsCommand;
562			}
563		}
564
565		void SaveAsCatalog()
566		{
567			try
568			{
569				using (System.Windows.Forms.OpenFileDialog browser = new System.Windows.Forms.OpenFileDialog())
570				{
571                    browser.Filter = FileService.Instance.CatalogFilterAll;
572                    browser.FilterIndex = FileService.Instance.CatalogFilterDefaultIndex;
573                    browser.DefaultExt = FileService.Instance.CatalogFilterDefaultExtension;
574
575                    if (browser.ShowDialog(new Wpf32Window()) == System.Windows.Forms.DialogResult.OK)
576					{
577                        CatalogService.Instance.SaveAs(Data, browser.FileName);
578					}
579				}
580			}
581			catch (Exception err)
582			{
583				ExceptionHelper.Manage("MainViewModel:SaveAsCatalog", err);
584			}
585		}
586		#endregion
587
588		#region refresh catalog command
589		private ICommand catalogRefreshCommand;
590        public ICommand CatalogRefreshCommand
591		{
592			get
593			{
594                if (catalogRefreshCommand == null)
595                    catalogRefreshCommand = new DelegateCommand(RefreshCatalog,
596						delegate()
597						{
598                            return (Data != null);
599						});
600                return catalogRefreshCommand;
601			}
602		}
603
604		void RefreshCatalog()
605		{
606            CatalogService.Instance.Refresh(Data);
607		}
608		#endregion
609
610		#region close catalog command
611		private ICommand catalogCloseCommand;
612		public ICommand CatalogCloseCommand
613		{
614			get
615			{
616                if (catalogCloseCommand == null)
617                    catalogCloseCommand = new DelegateCommand(CloseCatalog,
618						delegate()
619						{
620                            return Data != null;
621						});
622                return catalogCloseCommand;
623			}
624		}
625
626		void CloseCatalog()
627		{
628            if (Data != null)
629			{
630                if (CatalogService.Instance.IsDirty(Data))
631				{
632					if( MessageBox.Show( "Save the catalog and book changes ?", "Warning", MessageBoxButton.YesNo ) == MessageBoxResult.Yes )
633                        CatalogService.Instance.Save(Data);
634				}
635
636                Mediator.Instance.NotifyColleagues<Catalog>(ViewModelMessages.CatalogChanged, null);
637			}
638		}
639		#endregion
640		
641		#endregion
642
643        #region ----------------INTERNALS----------------
644
645		internal void SwapTwoPageMode(BookViewModelBase o)
646		{
647			ViewModels.Remove(o);
648
649			BookViewModelBase newModel = null;
650			BookViewModelBase oldModel = null;
651			if (o is ComicViewModel)
652			{
653				ComicViewModel comic = o as ComicViewModel;
654				newModel = new TwoPageViewModel(o.Data, comic.CurrentPage.Index, comic.FitMode, comic.PreviousScale);
655
656			}
657			else
658			{
659				TwoPageViewModel comic = o as TwoPageViewModel;
660				newModel = new ComicViewModel(o.Data, comic.CurrentPageIndex, comic.FitMode, comic.PreviousScale);
661
662			}
663
664			oldModel = o;
665			ViewModels.Add(newModel);
666			SetActiveView(newModel);
667
668			ViewModels.Remove(oldModel);
669		}
670
671        internal void ExecuteDistantCommand(CommandContext context)
672        {
673            if (context != null)
674            {
675                new ReflectionHelper().ExecuteICommand( this, context.CommandName, context.CommandParameter );
676            }
677        }
678
679        public void SetActiveView(ViewModelBase wmb)
680        {
681            if (wmb != null)
682            {
683                ICollectionView collectionView = CollectionViewSource.GetDefaultView(this.ViewModels);
684                if (collectionView != null)
685                    collectionView.MoveCurrentTo(wmb);
686            }
687        }
688
689        #endregion
690    }
691}