PageRenderTime 49ms CodeModel.GetById 13ms app.highlight 29ms RepoModel.GetById 1ms app.codeStats 0ms

/CBR/CBR/Views/MainView.xaml.cs

#
C# | 471 lines | 332 code | 60 blank | 79 comment | 34 complexity | 2d62ae9a936881be35844b825f6b27bd MD5 | raw file
  1using System;
  2using System.IO;
  3using System.Linq;
  4using System.Threading;
  5using System.Threading.Tasks;
  6using System.Windows;
  7using System.Windows.Threading;
  8using CBR.Components.Dialogs;
  9using CBR.Core.Helpers;
 10using CBR.Core.Helpers.Localization;
 11using CBR.Core.Helpers.Splash;
 12using CBR.Core.Helpers.State;
 13using CBR.Core.Models;
 14using CBR.Core.Services;
 15using CBR.ViewModels;
 16using CBR.Views.Others;
 17using Fluent;
 18using GalaSoft.MvvmLight.Messaging;
 19using Xceed.Wpf.AvalonDock.Layout.Serialization;
 20
 21namespace CBR.Views
 22{
 23    /// <summary>
 24    /// Interaction logic for MainView.xaml
 25    /// </summary>
 26    public partial class MainView : RibbonWindow
 27    {
 28        #region ----------------CONSTRUCTOR----------------
 29
 30        private WMIEventWatcher _wmiWatcher = null;
 31
 32        /// <summary>
 33        /// Constructor
 34        /// </summary>
 35        public MainView(string[] param)
 36        {
 37			using (new TimeLogger("MainView.MainView"))
 38			{
 39				InitializeComponent();
 40
 41				if (!System.ComponentModel.DesignerProperties.GetIsInDesignMode(this))
 42				{
 43					DataContext = new MainViewModel(param.Count() > 0 ? param[0] : string.Empty);
 44
 45					Messenger.Default.Register<NotificationMessage>(this, "Color", (s) =>
 46					{
 47						Uri source = new Uri(
 48							string.Format("/CBR;Component/Resources/XAML/Colors/Colors.{0}.xaml", s.Notification),
 49							UriKind.Relative);
 50
 51						Uri source2 = new Uri(
 52							string.Format("/Fluent;Component/Themes/Office2010/{0}.xaml", s.Notification),
 53							UriKind.Relative);
 54					
 55						Application.Current.Resources.BeginInit();
 56						Application.Current.Resources.MergedDictionaries.RemoveAt(0);
 57						Application.Current.Resources.MergedDictionaries.RemoveAt(0);
 58						Application.Current.Resources.MergedDictionaries.Insert(0, (ResourceDictionary)Application.LoadComponent(source));
 59						Application.Current.Resources.MergedDictionaries.Insert(0, (ResourceDictionary)Application.LoadComponent(source2));
 60						Application.Current.Resources.EndInit();
 61					});
 62				} 
 63
 64				//start wmi watcher and load existing devices
 65				Task.Factory.StartNew(() =>
 66				{
 67					try
 68					{
 69						_wmiWatcher = new WMIEventWatcher();
 70						_wmiWatcher.StartWatchUSB();
 71						_wmiWatcher.EventArrived += new WMIEventArrived(wmi_EventArrived);
 72					}
 73					catch (Exception err)
 74					{
 75						LogHelper.Manage("MainView.MainView start wmi watcher", err);
 76					}
 77				});
 78
 79				//start task to manage ByCode translations
 80				Task.Factory.StartNew(() =>
 81				{
 82					try
 83					{
 84						CultureManager.Instance.GetLocalization("ByCode", "Warning", "Warning");
 85						CultureManager.Instance.GetLocalization("ByCode", "Warning.Save", "Save the catalog and book changes ?");
 86						CultureManager.Instance.GetLocalization("ByCode", "Warning.Delete", "Please, confirm the deletion");
 87						CultureManager.Instance.GetLocalization("ByCode", "Warning.ScanFolder", "Your book folder is allready defined. Do you want to replace it ? Refreshing will work only with the new one.");
 88						CultureManager.Instance.GetLocalization("ByCode", "Warning.CatalogPath", "Catalog path does not exist! Please check the options box");
 89
 90						CultureManager.Instance.GetLocalization("ByCode", "DocumentTitle.Home", "Home");
 91						CultureManager.Instance.GetLocalization("ByCode", "DocumentTitle.Drives", "Drives");
 92						CultureManager.Instance.GetLocalization("ByCode", "DocumentTitle.Libraries", "Libraries");
 93
 94						CultureManager.Instance.GetLocalization("ByCode", "ExplorerView.Title", "Library Explorer");
 95						CultureManager.Instance.GetLocalization("ByCode", "TocView.Title", "Table of content");
 96						CultureManager.Instance.GetLocalization("ByCode", "DriveExplorerView.Title", "Drive Explorer");
 97
 98						CultureManager.Instance.GetLocalization("ByCode", "MEGA", "(Mb)");
 99						CultureManager.Instance.GetLocalization("ByCode", "KILO", "(Kb)");
100						CultureManager.Instance.GetLocalization("ByCode", "Convert.Start", "Starting conversion...");
101						CultureManager.Instance.GetLocalization("ByCode", "Convert.ParsingFolder", "Parsing folder {0}...");
102						CultureManager.Instance.GetLocalization("ByCode", "Convert.Converting", "Converting {0}...");
103						CultureManager.Instance.GetLocalization("ByCode", "Convert.ImageFound", "{0} images founded...");
104						CultureManager.Instance.GetLocalization("ByCode", "Convert.ImageSaved", "{0} images saved...");
105						CultureManager.Instance.GetLocalization("ByCode", "Convert.ImageCountingKO", "Extracting {0} : {1} images for {2} pages - Try to merge !");
106						CultureManager.Instance.GetLocalization("ByCode", "Convert.ImageMerge", "Merge to {0} new images...");
107						CultureManager.Instance.GetLocalization("ByCode", "Convert.ImageError", "Error extracting {0} : {1} images for {2} pages !!");
108						CultureManager.Instance.GetLocalization("ByCode", "Convert.ImageCountingOK", "Extracting {0} images in {1} pages");
109						CultureManager.Instance.GetLocalization("ByCode", "Convert.ImageExtracted", "{0} images extracted...");
110						CultureManager.Instance.GetLocalization("ByCode", "Convert.ImageZipped", "{0} images zipped...");
111						CultureManager.Instance.GetLocalization("ByCode", "Convert.Output", "Output file written !");
112					}
113					catch (Exception err)
114					{
115						LogHelper.Manage("MainView.MainView start localize", err);
116					}
117				});
118			}
119        }
120
121        #endregion
122
123        #region ----------------OTHERS----------------
124
125        /// <summary>
126        /// Display the about box
127        /// </summary>
128        /// <param name="sender"></param>
129        /// <param name="e"></param>
130        private void btnAbout_Click(object sender, RoutedEventArgs e)
131        {
132            AboutDialog dlg = new AboutDialog();
133            dlg.Owner = Application.Current.MainWindow;
134            dlg.ShowDialog();
135        }
136        #endregion
137
138        #region ----------------FULL SCREEN----------------
139
140        /// <summary>
141        /// Full screen state
142        /// </summary>
143        private bool IsFullScreen { get; set; }
144		private WindowState FullScreenPreviousMode { get; set; }
145
146        /// <summary>
147        /// full screen button click handler (binding is not working...)
148        /// </summary>
149        /// <param name="sender"></param>
150        /// <param name="e"></param>
151        private void btnFullScreen_Click(object sender, RoutedEventArgs e)
152        {
153            SwapFullScreenMode();
154        }
155
156        /// <summary>
157        /// Change the full screen state
158        /// </summary>
159        private void SwapFullScreenMode()
160        {
161            try
162            {
163                if (IsFullScreen)
164                {
165					this.WindowState = FullScreenPreviousMode;
166                    IsFullScreen = false;
167                }
168                else
169                {
170					FullScreenPreviousMode = this.WindowState;
171                    this.WindowState = WindowState.Maximized;
172                    IsFullScreen = true;
173                }
174
175				if (WorkspaceService.Instance.Settings.Extended.ShowFullScreenOptimized)
176				{
177					this.GlassBorderThickness = IsFullScreen ? new Thickness(0, 0, 0, 0) : new Thickness(8, 50, 8, 8);
178					this.statusBarInfo.Visibility = IsFullScreen ? Visibility.Collapsed : Visibility.Visible;
179					this.ribbonMain.Visibility = IsFullScreen ? Visibility.Collapsed : Visibility.Visible;
180				}
181				else
182				{
183					this.ribbonMain.IsMinimized = IsFullScreen;
184				}
185			}
186            catch (Exception err)
187            {
188                LogHelper.Manage("MainView:SwapFullScreenMode", err);
189            }
190        }
191        
192        #endregion
193
194        #region ----------------WINDOW EVENTS----------------
195
196        /// <summary>
197        /// handle file drop on the main surface
198        /// </summary>
199        /// <param name="sender"></param>
200        /// <param name="e"></param>
201        private void RibbonWindow_Drop(object sender, DragEventArgs e)
202        {
203            try
204            {
205                if (e.Data.GetDataPresent(DataFormats.FileDrop))
206                {
207                    MainViewModel mvm = DataContext as MainViewModel;
208
209                    string[] droppedFilePaths = e.Data.GetData(DataFormats.FileDrop, true) as string[];
210
211                    if (DocumentFactory.Instance.FindCatalogFilterByExt(System.IO.Path.GetExtension(droppedFilePaths[0])) != null)
212                        mvm.CatalogOpenFileCommand.Execute(droppedFilePaths[0]);
213                    else
214                    if (DocumentFactory.Instance.FindBookFilterByExtWithModel(System.IO.Path.GetExtension(droppedFilePaths[0])) != null)
215                        mvm.BookOpenFileCommand.Execute(droppedFilePaths[0]);
216                }
217            }
218            catch (Exception err)
219            {
220                LogHelper.Manage("MainView:RibbonWindow_Drop", err);
221            }
222        }
223
224        /// <summary>
225        /// start wmi watcher and load existing devices
226        /// </summary>
227        /// <param name="sender"></param>
228        /// <param name="e"></param>
229        private void RibbonWindow_Loaded(object sender, RoutedEventArgs e)
230        {
231			if (LogHelper.CanDebug())
232				LogHelper.Begin("MainView.RibbonWindow_Loaded");
233			try
234			{
235				SplashScreenManager.Splash.Message = "Localizing...";
236
237				LoadLayout("AvalonDockConfig.xml");
238
239				CultureManager.Instance.AvailableCulturesChanged += new CultureEventArrived(CultureManager_AvailableCulturesChanged);
240
241				MainViewModel mvm = DataContext as MainViewModel;
242
243				if (mvm != null)
244				{
245					//add all existing disks
246                    foreach (LogicalDiskInfo disk in _wmiWatcher.Devices)
247						mvm.SysDeviceAddCommand.Execute(disk);
248				}
249				
250				this.WindowState = System.Windows.WindowState.Maximized;
251				this.Visibility = System.Windows.Visibility.Visible;
252                this.Activate();
253			}
254			catch (Exception err)
255			{
256				LogHelper.Manage("MainView.RibbonWindow_Loaded", err);
257			}
258			finally
259			{
260				LogHelper.End("MainView.RibbonWindow_Loaded");
261			}  
262        }
263
264		/// <summary>
265		/// dispose the splash window
266		/// </summary>
267		/// <param name="sender"></param>
268		/// <param name="e"></param>
269		private void RibbonWindow_Activated(object sender, EventArgs e)
270		{
271			SplashScreenManager.Splash.Dispose();
272		}
273
274        /// <summary>
275        /// on closing, stop wmi watcher
276        /// </summary>
277        /// <param name="sender"></param>
278        /// <param name="e"></param>
279        private void RibbonWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
280        {
281            CultureManager.Instance.AvailableCulturesChanged -= new CultureEventArrived(CultureManager_AvailableCulturesChanged);
282
283			if( _wmiWatcher != null )
284				_wmiWatcher.StopWatchUSB();
285
286			SaveLayout("AvalonDockConfig.xml");
287        }
288
289        /// <summary>
290        /// Update the language menu
291        /// </summary>
292        /// <param name="sender"></param>
293        /// <param name="e"></param>
294        private void CultureManager_AvailableCulturesChanged(object sender, CultureEventArgs e)
295        {
296            MainViewModel mvm = DataContext as MainViewModel;
297
298            if (mvm != null)
299                mvm.Languages.Add( new LanguageMenuItemViewModel( e.Culture ) );
300        }
301
302        #endregion
303
304        #region ----------------OTHER EVENTS----------------
305
306        /// <summary>
307        /// handle wmi events
308        /// </summary>
309        /// <param name="sender"></param>
310        /// <param name="e"></param>
311        void wmi_EventArrived(object sender, WMIEventArgs e)
312        {
313            Application.Current.Dispatcher.BeginInvoke(DispatcherPriority.DataBind, (ThreadStart)delegate
314            {
315                MainViewModel mvm = DataContext as MainViewModel;
316
317                if (mvm != null)
318                {
319                    if (e.EventType == WMIActions.Added)
320                        mvm.SysDeviceAddCommand.Execute(e.Disk);
321                    else
322                        if (e.EventType == WMIActions.Removed)
323                            mvm.SysDeviceRemoveCommand.Execute(e.Disk);
324                }
325            });
326        }
327
328		/// <summary>
329		/// hnadle the key down event in the book ribbon for goto page function
330		/// </summary>
331		/// <param name="sender"></param>
332		/// <param name="e"></param>
333        private void PageNumber_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
334        {
335            if (e.Key == System.Windows.Input.Key.Enter)
336            {
337                MainViewModel mvm = DataContext as MainViewModel;
338
339				if (mvm != null && mvm.ActiveDocument is BookViewModelBase)
340                {
341					(mvm.ActiveDocument as BookViewModelBase).BookGotoPageCommand.Execute(this.PageNumber.Text);
342                }
343            }
344        }
345
346		/// <summary>
347		/// Update the culture regarding the dropdown selection
348		/// </summary>
349		/// <param name="sender"></param>
350		/// <param name="e"></param>
351        private void languageGallery_SelectionChanged(object sender, System.Windows.Controls.SelectionChangedEventArgs e)
352        {
353			if( e.AddedItems.Count>0)
354				CultureManager.Instance.UICulture = (e.AddedItems[0] as LanguageMenuItemViewModel).Data;
355        }
356
357		/// <summary>
358		/// Show localization editor
359		/// </summary>
360		/// <param name="sender"></param>
361		/// <param name="e"></param>
362        private void btnLocalize_Click(object sender, RoutedEventArgs e)
363        {
364            LocalizeView view = new LocalizeView();
365            view.Show();
366        }
367
368		/// <summary>
369		/// manage escaping the full screen mode when optimized
370		/// </summary>
371		/// <param name="sender"></param>
372		/// <param name="e"></param>
373		private void RibbonWindow_PreviewKeyUp(object sender, System.Windows.Input.KeyEventArgs e)
374		{
375			if ( e.Key == System.Windows.Input.Key.Escape && IsFullScreen )
376			{
377				SwapFullScreenMode();
378				e.Handled = true;
379			}
380		}
381
382		private void FeedMenuItem_Click(object sender, RoutedEventArgs e)
383		{
384			MainViewModel mvm = this.DataContext as MainViewModel;
385
386			FeedViewModel fvm = new FeedViewModel(((sender as MenuItem).DataContext) as FeedItemInfo);
387
388			mvm.Documents.Add(fvm);
389			mvm.SetActiveWorkspace(fvm);
390		}
391
392		#endregion
393
394		private void LoadLayout( string fileName )
395		{
396			if (LogHelper.CanDebug())
397				LogHelper.Begin("MainView.LoadLayout");
398			try
399			{
400				MainViewModel mvm = this.DataContext as MainViewModel;
401				string filePath = DirectoryHelper.Combine(CBRFolders.Cache, fileName);
402
403				if (File.Exists(filePath))
404				{
405					var serializer = new XmlLayoutSerializer(dockManager);
406					serializer.LayoutSerializationCallback += (s, e) =>
407					{
408                        if (!string.IsNullOrEmpty(e.Model.ContentId))
409                        {
410                            e.Content = ViewModelFactory.Instance.CreateFrom(mvm, e.Model.ContentId);
411                        }
412					};
413
414					using (var stream = new StreamReader(filePath))
415						serializer.Deserialize(stream);
416				}
417				else
418				{
419                    mvm.ResetLayout();
420                    SaveLayout("AvalonDockBackup.xml"); 
421				}
422			}
423			catch (Exception err)
424			{
425				LogHelper.Manage("MainView.LoadLayout", err);
426			}
427			finally
428			{
429				LogHelper.End("MainView.LoadLayout");
430			}  
431		}
432
433		private void SaveLayout( string fileName )
434		{
435			if (LogHelper.CanDebug())
436				LogHelper.Begin("MainView.SaveLayout");
437			try
438			{
439				var serializer = new XmlLayoutSerializer(dockManager);
440
441				string filePath = DirectoryHelper.Combine(CBRFolders.Cache, fileName);
442
443				using (var stream = new StreamWriter(filePath))
444					serializer.Serialize(stream);
445			}
446			catch (Exception err)
447			{
448				LogHelper.Manage("MainView.SaveLayout", err);
449			}
450			finally
451			{
452				LogHelper.End("MainView.SaveLayout");
453			}  
454		}
455
456		private void ButtonResetLayout_Click(object sender, RoutedEventArgs e)
457		{
458            MainViewModel mvm = this.DataContext as MainViewModel;
459            mvm.ResetLayout();
460            
461            //avalon
462			//LoadLayout("AvalonDockBackup.config");
463			
464            //fluent
465			this.ribbonMain.ClearQuickAccessToolBar();
466			
467            //grid
468			ElementStateOperations.Reset();
469		}
470	}
471}