Beispiel #1
0
        void AddinBaseOnStartup(object sender, EventArgs eventArgs)
        {
            VstoContribLog.Debug(_ => _("AddinBase.Startup raised, initialising ribbon factory controller"));
            context.AddinBase.Startup -= AddinBaseOnStartup;

            InitialiseRibbonFactoryController(ribbonFactoryController, context.Application);
        }
        void WordApplicationOnDocumentChange()
        {
            var enumDescription = WordRibbonType.WordDocument.GetEnumDescription();

            if (wordApplication.Documents.Count == 0)
            {
                VstoContribLog.Debug(_ => _("Application.DocumentChange raised, no documents currently open"));
                foreach (var viewInstance in wordApplication.Windows)
                {
                    NewView(this, new NewViewEventArgs(viewInstance, null, enumDescription));
                }
            }
            else
            {
                var activeDocument = wordApplication.ActiveDocument;
                if (closedDocuments.Contains(activeDocument.GetHashCode()))
                {
                    VstoContribLog.Debug(_ => _("Application.DocumentChange raised ActiveDocument: {0} is closing, ignoring event", activeDocument.ToLogFormat()));
                    return;
                }
                var activeWindow = wordApplication.ActiveWindow;
                VstoContribLog.Debug(_ => _("Application.DocumentChange raised, ActiveDocument: {0}, ActiveWindow: {1}",
                                            activeDocument.ToLogFormat(), activeWindow.ToLogFormat()));
                NewView(this, new NewViewEventArgs(activeWindow, activeDocument, enumDescription));
            }
        }
        public void RibbonLoaded(IRibbonUI ribbonUi)
        {
            ribbonUiLookup.Add(currentlyLoadingRibbon, ribbonUi);

            VstoContribLog.Debug(_ => _("ribbonTypeLookup.ContainsKey({0}) = {1}", currentlyLoadingRibbon, ribbonTypeLookup.ContainsKey(currentlyLoadingRibbon)));

            if (!ribbonTypeLookup.ContainsKey(currentlyLoadingRibbon))
            {
                return;
            }
            var viewModelType = ribbonTypeLookup[currentlyLoadingRibbon];

            foreach (var viewModelLookup in contextToViewModelLookup.Values
                     .Where(viewModel => viewModel.GetType() == viewModelType && viewModel.RibbonUi == null))
            {
                VstoContribLog.Debug(_ => _("Setting RibbonUi [{0}] for ViewModel", ribbonUi.ToLogFormat()));
                viewModelLookup.RibbonUi = ribbonUi;
                InvalidateRibbonForViewModel(viewModelLookup);
            }

            if (!ribbonUiLookup.ContainsKey(DefaultRibbon))
            {
                ribbonUiLookup[DefaultRibbon] = ribbonUi;
            }
        }
        private void CleanupViewModel(object context)
        {
            VstoContribLog.Debug(_ => _("Cleaning up viewmodel for context: {0}", context.ToLogFormat()));
            if (!contextToViewModelLookup.ContainsKey(context))
            {
                VstoContribLog.Warn(_ => _("Cannot find ViewModel to cleanup: {0}", context.ToLogFormat()));
                return;
            }

            var viewModelInstance = contextToViewModelLookup[context];

            VstoContribLog.Info(_ => _("ViewModel is {0}", viewModelInstance.ToLogFormat()));

            var notifyOfPropertyChanged = viewModelInstance as INotifyPropertyChanged;

            if (notifyOfPropertyChanged != null)
            {
                notifyOfPropertyChanged.PropertyChanged -= NotifiesOfPropertyChangedPropertyChanged;
            }

            viewModelInstance.Cleanup();
            vstoContribContext.ViewModelFactory.Release(viewModelInstance);
            customTaskPaneRegister.CleanupViewModel(viewModelInstance);
            contextToViewModelLookup.Remove(context);
        }
        private IRibbonViewModel BuildViewModel(string ribbonType, object viewInstance, object viewContext)
        {
            var viewModelType = ribbonTypeLookup[ribbonType];

            VstoContribLog.Info(_ => _("Building ViewModel of type {1} for ribbon {1} with context {2}",
                                       viewModelType.Name, ribbonType, viewContext.ToLogFormat()));
            var ribbonViewModel = vstoContribContext.ViewModelFactory.Resolve(viewModelType);

            ribbonViewModel.VstoFactory = vstoContribContext.VstoFactory;

            if (ribbonUiLookup.ContainsKey(ribbonType))
            {
                var ribbonUi = ribbonUiLookup[ribbonType];
                VstoContribLog.Debug(_ => _("Setting RibbonUi [{0}] for ViewModel", ribbonUi.ToLogFormat()));
                ribbonViewModel.RibbonUi = ribbonUi;
            }
            else if (ribbonUiLookup.ContainsKey(DefaultRibbon))
            {
                var ribbonUi = ribbonUiLookup[DefaultRibbon];
                VstoContribLog.Info(_ => _("Ribbon type was not found, but default was. Setting RibbonUi [{0}] for ViewModel", ribbonUi.ToLogFormat()));
                ribbonViewModel.RibbonUi = ribbonUi;
            }


            ribbonViewModel.CurrentView = viewInstance;
            ListenForINotifyPropertyChanged(ribbonViewModel);
            ribbonViewModel.Initialised(viewContext == NullContext.Instance ? null : viewContext);

            return(ribbonViewModel);
        }
Beispiel #6
0
        void MonitorWorkbookClosed(object sender, WorkbookClosedEventArgs e)
        {
            VstoContribLog.Debug(log => log("Excel raised WorkbookClosed({0}) event", e.Workbook.ToLogFormat()));
            var handler = ViewClosed;

            if (handler == null)
            {
                return;
            }

            if (workbooks.ContainsKey(e.Workbook))
            {
                var windows = workbooks[e.Workbook];

                foreach (var window in windows)
                {
                    handler(this, new ViewClosedEventArgs(window, e.Workbook));
                    if (!IsMdi())
                    {
                        window.ReleaseComObject();
                    }
                }
                workbooks.Remove(e.Workbook);
            }

            if (!excelApplication.Workbooks.OfType <Workbook>().Except(new[] { e.Workbook }).Any())
            {
                nullContextOpen = true;
                foreach (Window window in excelApplication.Windows)
                {
                    NewView(this, new NewViewEventArgs(window, NullContext.Instance, ExcelRibbonType.ExcelWorkbook.GetEnumDescription()));
                }
            }
        }
Beispiel #7
0
        // ReSharper restore InconsistentNaming

        /// <summary>
        /// Gets the custom UI.
        /// </summary>
        /// <param name="ribbonId">The ribbon id.</param>
        /// <returns></returns>
        public string GetCustomUI(string ribbonId)
        {
            VstoContribLog.Info(_ => _("Office called GetCustomUI({0})", ribbonId));
            var customUI = ribbonFactoryController.GetCustomUI(ribbonId);

            VstoContribLog.Debug(_ => _("Provided ribbon xml for ribbonId {0}:\r\n\r\n{1}", ribbonId, customUI));
            return(customUI);
        }
        public void Invoke(IRibbonControl control, Expression <Action> caller, params object[] parameters)
        {
            try
            {
                var            methodName     = caller.GetMethodName();
                CallbackTarget callbackTarget =
                    vstoContribContext.TagToCallbackTargetLookup[control.Tag + methodName];

                var view = (object)control.Context;
                IRibbonViewModel viewModelInstance = ribbonViewModelResolver.ResolveInstanceFor(view);
                VstoContribLog.Debug(l => l("Ribbon callback {0} being invoked on {1} (View: {2}, ViewModel: {3})",
                                            methodName, control.Id, view.ToLogFormat(), viewModelInstance.ToLogFormat()));

                Type         type     = viewModelInstance.GetType();
                PropertyInfo property = type.GetProperty(callbackTarget.Method);

                if (property != null)
                {
                    type.InvokeMember(callbackTarget.Method,
                                      BindingFlags.SetProperty,
                                      null,
                                      viewModelInstance,
                                      new[]
                    {
                        parameters.Single()
                    });
                }
                else
                {
                    type.InvokeMember(callbackTarget.Method,
                                      BindingFlags.InvokeMethod,
                                      null,
                                      viewModelInstance,
                                      new[]
                    {
                        control
                    }
                                      .Concat(parameters)
                                      .ToArray());
                }
            }
            catch (TargetInvocationException e)
            {
                var innerEx = e.InnerException;
                PreserveStackTrace(innerEx);
                if (vstoContribContext.ErrorHandlers.Count == 0)
                {
                    Trace.TraceError(innerEx.ToString());
                }

                var handled = vstoContribContext.ErrorHandlers.Any(errorHandler => errorHandler.Handle(innerEx));

                if (!handled)
                {
                    throw innerEx;
                }
            }
        }
        void ViewProviderViewClosed(object sender, ViewClosedEventArgs e)
        {
            VstoContribLog.Debug(_ => _("ViewProvider.ViewClosed Raised, View: {0}, Context: {1}",
                                        e.View.ToLogFormat(), e.Context.ToLogFormat()));
            //TODO write test around context/view cleanup
            customTaskPaneRegister.Cleanup(e.View);

            CleanupViewModel(e.Context);
            viewProvider.CleanupReferencesTo(e.View, e.Context);
        }
        public object InvokeGet(IRibbonControl control, Expression <Action> caller, params object[] parameters)
        {
            if (control.Context == null)
            {
                return(null);
            }

            var            methodName     = caller.GetMethodName();
            CallbackTarget callbackTarget = vstoContribContext.TagToCallbackTargetLookup[control.Tag + methodName];

            var view = (object)control.Context;
            IRibbonViewModel viewModelInstance = ribbonViewModelResolver.ResolveInstanceFor(view);

            VstoContribLog.Debug(l => l("Ribbon callback {0} being invoked on {1} (View: {2}, ViewModel: {3})",
                                        methodName, control.Id, view.ToLogFormat(), viewModelInstance.ToLogFormat()));

            Type         type     = viewModelInstance.GetType();
            PropertyInfo property = type.GetProperty(callbackTarget.Method);

            if (property != null)
            {
                return(type.InvokeMember(callbackTarget.Method,
                                         BindingFlags.GetProperty,
                                         null,
                                         viewModelInstance,
                                         null));
            }

            try
            {
                return(type.InvokeMember(callbackTarget.Method,
                                         BindingFlags.InvokeMethod,
                                         null,
                                         viewModelInstance,
                                         new[]
                {
                    control
                }
                                         .Concat(parameters)
                                         .ToArray()));
            }
            catch (MissingMethodException)
            {
                throw new InvalidOperationException(
                          string.Format("Expecting method with signature: {0}.{1}(IRibbonControl control)",
                                        type.Name,
                                        callbackTarget.Method));
            }
        }
        void NotifiesOfPropertyChangedPropertyChanged(object sender, PropertyChangedEventArgs e)
        {
            var viewModel  = (IRibbonViewModel)sender;
            var senderType = sender.GetType();

            foreach (var invalidatedControl in
                     notifyChangeTargetLookup[senderType]
                     .Where(property => property.Key == e.PropertyName)
                     .Select(pair => pair.Value)
                     .Distinct()
                     .Where(invalidatedControl => viewModel.RibbonUi != null))
            {
                VstoContribLog.Debug(_ => _("Invalidating {0} due to property change notification", invalidatedControl));
                viewModel.RibbonUi.InvalidateControl(invalidatedControl);
            }
        }
 /// <summary>
 /// Registers the open word documents.
 /// </summary>
 public void RegisterOpenDocuments()
 {
     VstoContribLog.Debug(_ => _("Registering all already open documents"));
     using (var documents = wordApplication.Documents.WithComCleanup())
     {
         foreach (Document document in documents.Resource)
         {
             using (var windows = document.Windows.WithComCleanup())
             {
                 foreach (Window window in windows.Resource)
                 {
                     WordApplicationWindowActivate(document, window);
                 }
             }
         }
     }
 }
Beispiel #13
0
 void Activate(Workbook wb, Window wn)
 {
     VstoContribLog.Debug(log => log("Excel raised WorkbookOpen(wb: {0}, wn: {1}) event", wb.ToLogFormat(), wn.ToLogFormat()));
     if (IsMdi() && !workbooks[wb].Contains(singleWindow))
     {
         workbooks[wb].Add(singleWindow);
     }
     if (!IsMdi() && !workbooks[wb].Contains(wn))
     {
         var windows = workbooks[wb];
         if (windows.All(w => ((dynamic)w).Hwnd != ((dynamic)wn).Hwnd))
         {
             windows.Add(wn);
             NewView(this, new NewViewEventArgs(wn, wb, ExcelRibbonType.ExcelWorkbook.GetEnumDescription()));
         }
     }
 }
        static IEnumerable <Type> GetTRibbonTypesInAssemblies(IEnumerable <Assembly> assemblies)
        {
            VstoContribLog.Debug(_ => _("Discovering ViewModels"));

            Type ribbonViewModelType = typeof(IRibbonViewModel);

            return(assemblies
                   .Select(assembly =>
            {
                VstoContribLog.Debug(_ => _("Discovering ViewModels in {0}", assembly.GetName().Name));
                var types = assembly.GetTypes();
                var viewModelTypes = types.Where(ribbonViewModelType.IsAssignableFrom).ToArray();
                VstoContribLog.Debug(_ => _("Found:{0}", string.Join(string.Empty, viewModelTypes.Select(vm => "\r\n  " + vm.Name))));
                return viewModelTypes;
            }
                           )
                   .SelectMany(vm => vm));
        }
        void ViewProviderNewView(object sender, NewViewEventArgs e)
        {
            VstoContribLog.Debug(_ => _("ViewProvider.NewView Raised, Type: {0}, View: {1}, Context: {2}",
                                        e.RibbonType, e.ViewInstance.ToLogFormat(), e.ViewContext.ToLogFormat()));
            if (ribbonUiLookup.ContainsKey("default"))
            {
                ribbonUiLookup.Add(e.RibbonType, ribbonUiLookup["default"]);
                ribbonUiLookup.Remove("default");
            }
            var viewModel = GetOrCreateViewModel(e.RibbonType, e.ViewContext ?? NullContext.Instance, e.ViewInstance);

            if (viewModel == null)
            {
                return;
            }
            customTaskPaneRegister.RegisterCustomTaskPanes(viewModel, e.ViewInstance, e.ViewContext);
            InvalidateRibbonForViewModel(viewModel);
            e.Handled = true;
        }
        IRibbonViewModel GetOrCreateViewModel(string ribbonType, object viewContext, object viewInstance)
        {
            if (!ribbonTypeLookup.ContainsKey(ribbonType))
            {
                return(null);
            }
            if (contextToViewModelLookup.ContainsKey(viewContext))
            {
                //Tell viewmodel there is a new view active
                var ribbonViewModel = contextToViewModelLookup[viewContext];
                VstoContribLog.Debug(_ => _("ViewModel {0} found for context {1}", ribbonViewModel.ToLogFormat(), viewContext.ToLogFormat()));
                ribbonViewModel.CurrentView = viewInstance;
                return(ribbonViewModel);
            }

            currentlyLoadingRibbon = ribbonType;
            IRibbonViewModel buildViewModel = BuildViewModel(ribbonType, viewInstance, viewContext);

            contextToViewModelLookup.Add(viewContext, buildViewModel);
            return(buildViewModel);
        }
Beispiel #17
0
 /// <summary>
 /// Ribbon_s the load.
 /// </summary>
 /// <param name="ribbonUi">The ribbon UI.</param>
 // ReSharper disable InconsistentNaming
 public virtual void Ribbon_Load(IRibbonUI ribbonUi)
 {
     VstoContribLog.Debug(_ => _("Ribbon_Load event raised: {0}", ribbonUi.ToLogFormat()));
     ribbonFactoryController.RibbonLoaded(ribbonUi);
 }
Beispiel #18
0
 void WorkbookOpen(Workbook wb)
 {
     VstoContribLog.Debug(log => log("Excel raised WorkbookOpen({0}) event", wb.ToLogFormat()));
     OnInitialise(wb);
 }
 void WordApplicationDocumentOpen(Document doc)
 {
     VstoContribLog.Debug(_ => _("Application.DocumentOpen raised, Document: {0}", doc.ToLogFormat()));
     WordApplicationWindowActivate(doc, doc.ActiveWindow);
 }