using Bovender.Mvvm.Actions; /* Commands.cs * part of zaaReloaded2 * * Copyright 2015-2017 Daniel Kraus * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using zaaReloaded2.Controller; using zaaReloaded2.Controller.Comments; using zaaReloaded2.Formatter; using zaaReloaded2.Importer.ZaaImporter; using zaaReloaded2.ViewModels; using zaaReloaded2.Views; using Word = Microsoft.Office.Interop.Word; namespace zaaReloaded2 { /// /// /// static class Commands { #region Command methods public static void Format() { if (CanFormat()) { SettingsRepository repository = SettingsRepository.Load(); Guid lastSettingsUid = UserSettings.Default.LastSettings; Settings lastSettings = repository.FindByGuid(lastSettingsUid); if (lastSettings != null) { DoFormat(lastSettings); } else { ChooseSettings(); } } } public static bool CanFormat() { return Globals.ThisAddIn.Application.ActiveDocument != null; //Word.Selection s = Globals.ThisAddIn.Application.ActiveWindow.Selection; //return s.Paragraphs.Count > 1 || // (s.Text.Length > 1 && s.Text.EndsWith("\r")); } public static void ChooseSettings() { SettingsRepository repository = SettingsRepository.Load(); SettingsRepositoryViewModel vm = new SettingsRepositoryViewModel(repository); vm.UseSettingsMessage.Sent += (sender, args) => { SettingsViewModel settingsVM = args.Content.ViewModel as SettingsViewModel; Settings settings = settingsVM.RevealModelObject() as Settings; DoFormat(settings); UserSettings.Default.LastSettings = settings.Uid; }; vm.InjectInto().ShowDialog(); } /// /// Loads the embedded demo document. /// /// /// If Word is running in an embedded environment (e.g. in the ZAA), /// adding a document causes a COMException. Unfortunately, it is /// not trivial to test if Word is running embedded, so we use a /// try...catch structure and catch all COMExceptions. The error /// message might be not quite right if the exception was caused by /// a different problem. /// See http://davecra.com/2013/04/10/how-to-determine-if-an-excel-workbook-is-embedded-and-more /// public static void LoadDemo() { try { Demo.Demo.OpenDemoDocument(); } catch (System.Runtime.InteropServices.COMException e) { // HRESULT comparison according to http://stackoverflow.com/a/1426198/270712 // Fix for exception ID 65a5c34e if (e.ErrorCode == unchecked((int)0x800A11FD)) { NotificationAction a = new NotificationAction(); a.Caption = "Kann Demo-Dokument nicht laden"; a.Message = "Das Demo-Dokument kann nicht geladen werden, " + "wenn Word in der Zentralen Arztbriefablage ausgeführt wird.\r" + "Bitte Word als eigenständige Anwendung starten und dann " + "noch einmal versuchen."; a.OkButtonText = "Schließen"; a.Invoke(); } else { throw; } } } public static void ShowAbout() { ViewModels.AboutViewModel vm = new ViewModels.AboutViewModel(); vm.InjectInto().ShowDialog(); } public static void ShowPreferences() { ViewModels.PreferencesViewModel vm = new PreferencesViewModel(); vm.InjectInto().ShowDialog(); } public static void ApplyDanielsStyle() { Formatter.DanielsStyle.Apply( Globals.ThisAddIn.Application.ActiveDocument, Globals.ThisAddIn.Application.Selection); } public static void FormatDrugs(int columns) { if (columns < 1 || columns > 2) { throw new ArgumentOutOfRangeException("Can only format 1 or 2 columns, not " + columns); } // If no "real" selection exists, attempt to auto-detect the drugs section. // (NB Technically, there is never _no_ selection in a document.) Word.Window activeWindow = Globals.ThisAddIn.Application.ActiveWindow; Word.Selection sel = activeWindow.Selection; Word.Paragraphs paragraphs = sel.Paragraphs; Word.Document document = activeWindow.Document; if (!(paragraphs.Count > 1 || (sel.Text.Length > 1 && sel.Text.EndsWith("\r")))) { Logger.Info("FormatDrugs: Attempting to auto-detect"); if (!Medication.Importer.AutoDetect(document)) { Logger.Info("FormatDrugs: Failed to auto-detect"); NotificationAction a = new NotificationAction(); a.Caption = "Formatieren nicht möglich"; a.Message = "Das Dokument scheint keine Medikationsliste zu enthalten."; a.OkButtonText = "Schließen"; a.Invoke(); return; } } Logger.Info("FormatDrugs: Importing"); Medication.Importer importer = new Medication.Importer(sel.Text); Medication.Formatter formatter = new Medication.Formatter(importer.Prescriptions); Logger.Info("FormatDrugs: Formatting"); switch (columns) { case 1: formatter.FormatOneColumn(document); break; case 2: formatter.FormatTwoColumns(document); break; default: break; } Logger.Info("FormatDrugs: Cleaning up"); Bovender.ComHelpers.ReleaseComObject(document); Bovender.ComHelpers.ReleaseComObject(paragraphs); Bovender.ComHelpers.ReleaseComObject(sel); Bovender.ComHelpers.ReleaseComObject(activeWindow); } #endregion #region Private methods private static void DoFormat(Settings settings) { // If no "real" selection exists, attempt to auto-detect the lab data. // (NB Technically, there is never _no_ selection in a document.) Word.Application word = Globals.ThisAddIn.Application; Word.Document activeDocument = word.ActiveDocument; Word.Window activeWindow = word.ActiveWindow; Word.Selection selection = activeWindow.Selection; Word.Paragraphs paragraphs = selection.Paragraphs; if (!(paragraphs.Count > 1 || (selection.Text.Length > 1 && selection.Text.EndsWith("\r")))) { Logger.Info("DoFormat: Attempting to auto-detect"); Word.Document doc = activeWindow.Document; if (!AutoDetect.Detect(doc)) { Logger.Info("DoFormat: Automatic detection failed"); NotificationAction a = new NotificationAction(); a.Caption = "Formatieren nicht möglich"; a.Message = "Das Dokument scheint keine Lauris-Labordaten zu enthalten."; a.OkButtonText = "Schließen"; a.Invoke(); return; } // Don't release the COM object here // Bovender.ComHelpers.ReleaseComObject(doc); } Logger.Info("DoFormat: Importing"); ZaaImporter importer = new ZaaImporter(); importer.Import(selection.Text); Formatter.Formatter formatter = new Formatter.Formatter(activeDocument); formatter.Settings = settings; formatter.Laboratory = importer.Laboratory; CommentPool.Default.Reset(); CommentPool.Default.FillInComment += CommentPool_FillInComment; try { Logger.Info("DoFormat: Formatting"); formatter.Run(); } catch (NoLaboratoryDataException e) { Logger.Warn("DoFormat: No lab data?!"); Logger.Warn(e); NotificationAction a = new NotificationAction(); a.Caption = "Formatieren nicht möglich"; a.Message = "Die aktuelle Markierung scheint keine Labordaten zu enthalten."; a.OkButtonText = "Schließen"; a.Invoke(); } Bovender.ComHelpers.ReleaseComObject(paragraphs); Bovender.ComHelpers.ReleaseComObject(selection); Bovender.ComHelpers.ReleaseComObject(activeWindow); Bovender.ComHelpers.ReleaseComObject(activeDocument); Logger.Info("DoFormat: Finished"); } private static void CommentPool_FillInComment(object sender, ItemCommentEventArgs e) { if (UserSettings.Default.SuppressItemCommentInteraction) { Logger.Info("CommentPool_FillInComment: Comment interaction is suppressed by user settings"); e.Comment.IsCancelled = true; } else { Logger.Info("CommentPool_FillInComment: Requesting user interaction"); ItemCommentViewModel vm = new ItemCommentViewModel(e.Comment); vm.InjectInto().ShowDialog(); } } #endregion #region Class logger private static NLog.Logger Logger { get { return _logger.Value; } } private static readonly Lazy _logger = new Lazy(() => NLog.LogManager.GetCurrentClassLogger()); #endregion } }