Wrappers/WatchedWindow.cs
branchOUT-497
changeset 2359 0e6191d039e4
child 2360 f01523e581fa
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/Wrappers/WatchedWindow.cs	Thu Sep 06 09:29:19 2018 +0200
     1.3 @@ -0,0 +1,1428 @@
     1.4 +´╗┐using pEp.UI;
     1.5 +using pEpCOMServerAdapterLib;
     1.6 +using System;
     1.7 +using System.ComponentModel;
     1.8 +using System.Windows.Forms;
     1.9 +using Outlook = Microsoft.Office.Interop.Outlook;
    1.10 +
    1.11 +namespace pEp
    1.12 +{
    1.13 +    /// <summary>
    1.14 +    /// Stores an Outlook Window with connected events.
    1.15 +    /// </summary>
    1.16 +    public abstract class WatchedWindow : IDisposable
    1.17 +    {
    1.18 +        private CryptableMailItem               cryptableMailItem           = null;
    1.19 +        private bool                            displayMirrorRequested      = false;
    1.20 +        private HandshakeDialog                 handshakeDialog             = null;
    1.21 +        private bool                            isEnabled                   = true;
    1.22 +        private bool                            isStarted                   = false;
    1.23 +        private bool                            processingOngoing           = false;
    1.24 +        private bool                            refreshOngoing              = false;
    1.25 +        private bool                            repeatProcessing            = false;
    1.26 +        private int                             repeatCounter               = 0;
    1.27 +        private const int                       maxRepeatCount              = 5;
    1.28 +
    1.29 +        private Outlook.MailItem                _CurrentMailItem            = null;
    1.30 +
    1.31 +        public enum WindowTypes
    1.32 +        {
    1.33 +            Undefined,
    1.34 +            Inspector,
    1.35 +            Explorer
    1.36 +        }
    1.37 +
    1.38 +        #region Properties
    1.39 +        /// <summary>
    1.40 +        /// The rating of the currently selected message.
    1.41 +        /// </summary>
    1.42 +        private pEpRating _Rating = pEpRating.pEpRatingUndefined;
    1.43 +
    1.44 +        /// <summary>
    1.45 +        /// The mail item that is connected to this Inspector/Explorer window.
    1.46 +        /// </summary>
    1.47 +        public Outlook.MailItem CurrentMailItem
    1.48 +        {
    1.49 +            get
    1.50 +            {
    1.51 +                return this._CurrentMailItem;
    1.52 +            }
    1.53 +            protected set
    1.54 +            {
    1.55 +                this._CurrentMailItem = value;
    1.56 +            }
    1.57 +        }
    1.58 +
    1.59 +        /// <summary>
    1.60 +        /// Gets or sets whether to disable the Force Protection option.
    1.61 +        /// </summary>
    1.62 +        public bool DisableForceProtection { get; set; } = false;
    1.63 +
    1.64 +        /// <summary>
    1.65 +        /// Gets or sets whether to send this message forcefully protected.
    1.66 +        /// </summary>
    1.67 +        public bool ForceProtection { get; set; } = false;
    1.68 +
    1.69 +        /// <summary>
    1.70 +        /// Gets or sets whether to send this message forcefully unencrypted.
    1.71 +        /// </summary>
    1.72 +        public bool ForceUnencrypted { get; set; } = false;
    1.73 +
    1.74 +        /// <summary>
    1.75 +        /// Gets or sets whether the message is a draft message.
    1.76 +        /// </summary>
    1.77 +        public bool IsDraft { get; set; } = false;
    1.78 +
    1.79 +        /// <summary>
    1.80 +        /// Gets or sets whether to always store this message as if on an untrusted server.
    1.81 +        /// </summary>
    1.82 +        public bool NeverUnsecure { get; set; } = false;
    1.83 +
    1.84 +        /// <summary>
    1.85 +        /// Gets the rating of this message.
    1.86 +        /// </summary>
    1.87 +        public pEpRating Rating
    1.88 +        {
    1.89 +            get { return this._Rating; }
    1.90 +        }
    1.91 +
    1.92 +        /// <summary>
    1.93 +        /// Gets the associated Explorer/Inspector window. To be overwritten by child class.
    1.94 +        /// </summary>
    1.95 +        public abstract dynamic Window { get; }
    1.96 +
    1.97 +        /// <summary>
    1.98 +        /// Sets the rating of this message and updates the UI.
    1.99 +        /// </summary>
   1.100 +        /// <param name="rating">The message rating.</param>
   1.101 +        public void SetRating(pEpRating rating)
   1.102 +        {
   1.103 +            this._Rating = rating;
   1.104 +            RibbonCustomizations.Invalidate();
   1.105 +        }
   1.106 +
   1.107 +        /// <summary>
   1.108 +        /// The timer that schedules the updates of this window.
   1.109 +        /// </summary>
   1.110 +        public System.Windows.Forms.Timer TimerRefresh { get; set; } = new System.Windows.Forms.Timer();
   1.111 +        #endregion
   1.112 +
   1.113 +        #region Constructors / Destructors
   1.114 +
   1.115 +        /// <summary>
   1.116 +        /// Destructor.
   1.117 +        /// </summary>
   1.118 +        ~WatchedWindow()
   1.119 +        {
   1.120 +            this.Dispose(true);
   1.121 +        }
   1.122 +        #endregion
   1.123 +
   1.124 +        #region Methods
   1.125 +        /**************************************************************
   1.126 +         * 
   1.127 +         * Methods
   1.128 +         * 
   1.129 +         *************************************************************/
   1.130 +
   1.131 +        /// <summary>
   1.132 +        /// Releases all resources and disconnects internal events.
   1.133 +        /// </summary>
   1.134 +        public void Dispose()
   1.135 +        {
   1.136 +            this.Dispose(true);
   1.137 +        }
   1.138 +
   1.139 +        /// <summary>
   1.140 +        /// Clean up any resources being used.
   1.141 +        /// </summary>
   1.142 +        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
   1.143 +        protected virtual void Dispose(bool disposing)
   1.144 +        {
   1.145 +            if (disposing)
   1.146 +            {
   1.147 +                // Set Outlook objects to null
   1.148 +                this._CurrentMailItem = null;
   1.149 +            }
   1.150 +        }
   1.151 +              
   1.152 +        /// <summary>
   1.153 +        /// Builds the latest state of the encryption status manager then shows the UI.
   1.154 +        /// </summary>
   1.155 +        public void BuildAndShowManager()
   1.156 +        {
   1.157 +            /* Resolve all recipients -- this ensures the identities list is correctly populated
   1.158 +             * 
   1.159 +             * Note: The PropertyChanged changed event must be disconnected before trying to resolve.
   1.160 +             * This is because the resolve process can modify the contents of the mail item which triggers an event.
   1.161 +             * The PropertyChanged event would then trigger a UI refresh cycle. However, because the GetManagerState itself 
   1.162 +             * is called within the UI refresh, an infinite loop could occur trying to resolve a recipient that
   1.163 +             * cannot be resolved (no address).
   1.164 +             */
   1.165 +            try
   1.166 +            {
   1.167 +                this.ResolveAllRecipients();
   1.168 +            }
   1.169 +            catch (Exception ex)
   1.170 +            {
   1.171 +                Log.Verbose("BuildAndShowManager: Error resolving recipients. " + ex.ToString());
   1.172 +            }
   1.173 +
   1.174 +            // Build the dialog
   1.175 +            try
   1.176 +            {
   1.177 +                // The PEPMessage to build the dialog with
   1.178 +                PEPMessage message = null;
   1.179 +
   1.180 +                // The own identity to build the dialog with
   1.181 +                PEPIdentity myself = this.cryptableMailItem?.Myself;
   1.182 +
   1.183 +                // If message is a draft, create it directly from the Outlook mail item
   1.184 +                if (this.IsDraft)
   1.185 +                {
   1.186 +                    Log.Verbose("BuildAndShowManager: Creating PEPMessage from draft.");
   1.187 +
   1.188 +                    if (PEPMessage.Create(this._CurrentMailItem, out message) != Globals.ReturnStatus.Success)
   1.189 +                    {
   1.190 +                        Log.Error("BuildAndShowManager: Error creating PEPMessage from draft.");
   1.191 +                        message = null;
   1.192 +                    }
   1.193 +                    else
   1.194 +                    {
   1.195 +                        // Calculate rating
   1.196 +                        message.Rating = message.GetOutgoingRating();
   1.197 +
   1.198 +                        // If Force Protection is set, assign a random GUID
   1.199 +                        if ((this.ForceProtection) &&
   1.200 +                            (this.DisableForceProtection == false))
   1.201 +                        {
   1.202 +                            message.ForceProtectionId = Guid.NewGuid().ToString();
   1.203 +                        }
   1.204 +
   1.205 +                        // If message is Force Unencrypted, assign it
   1.206 +                        message.ForceUnencrypted = this.ForceUnencrypted;
   1.207 +                    }
   1.208 +                }
   1.209 +                else
   1.210 +                {
   1.211 +                    // Else, use either the cryptable mail item's associated mirror or message
   1.212 +                    message = this.cryptableMailItem?.Mirror ?? this.cryptableMailItem?.Message;
   1.213 +                    Log.Verbose(string.Format("BuildAndShowManager: Message {0} retrieved from CryptableMailItem", ((message != null) ? "successfully" : "could not be")));
   1.214 +
   1.215 +                    // As fallback, if we don't have a message yet, create it
   1.216 +                    if (message == null)
   1.217 +                    {
   1.218 +                        Log.Verbose("BuildAndShowManager: Using fallback method to get message.");
   1.219 +
   1.220 +                        Outlook.MailItem mirror = null;
   1.221 +
   1.222 +                        try
   1.223 +                        {
   1.224 +                            // For securely stored mails, try to look up mirror
   1.225 +                            if (this._CurrentMailItem?.GetIsSecurelyStored() == true)
   1.226 +                            {
   1.227 +                                mirror = this._CurrentMailItem?.GetMirror();
   1.228 +
   1.229 +                                if (mirror != null)
   1.230 +                                {
   1.231 +                                    // If mirror is found, use it to create PEPMessage
   1.232 +                                    Log.Verbose("BuildAndShowManager: Mirror found.");
   1.233 +
   1.234 +                                    if (PEPMessage.Create(mirror, out message) != Globals.ReturnStatus.Success)
   1.235 +                                    {
   1.236 +                                        message = null;
   1.237 +                                        Log.Error("BuildAndShowManager: Error creating PEPMessage.");
   1.238 +                                    }
   1.239 +                                    else
   1.240 +                                    {
   1.241 +                                        message.Rating = AdapterExtensions.ReevaluateMessageRating(message);
   1.242 +                                    }
   1.243 +                                }
   1.244 +                                else
   1.245 +                                {
   1.246 +                                    // If no mirror is found, decrypt message and use decrypted one (do not 
   1.247 +                                    // decrypt forcefully protected messages).
   1.248 +                                    if ((PEPMessage.Create(this._CurrentMailItem, out message) == Globals.ReturnStatus.Success) &&
   1.249 +                                        (string.IsNullOrEmpty(message.ForceProtectionId)))
   1.250 +                                    {
   1.251 +                                        var msgProcessor = new MsgProcessor();
   1.252 +                                        PEPMessage decryptedMsg = null;
   1.253 +                                        string[] keyList;
   1.254 +                                        pEpDecryptFlags flags = pEpDecryptFlags.pEpDecryptFlagsNone;
   1.255 +                                        pEpRating rating = msgProcessor.Decrypt(ref message, out decryptedMsg, out keyList, ref flags);
   1.256 +                                        if (decryptedMsg != null)
   1.257 +                                        {
   1.258 +                                            message = decryptedMsg;
   1.259 +                                        }
   1.260 +                                        message.Rating = rating;
   1.261 +                                    }
   1.262 +                                    else
   1.263 +                                    {
   1.264 +                                        message = null;
   1.265 +                                        Log.Error("BuildAndShowManager: Error creating PEPMessage from mirror.");
   1.266 +                                    }
   1.267 +                                }
   1.268 +                            }
   1.269 +
   1.270 +                            // If we don't have a PEPMessage yet, create it
   1.271 +                            if (message == null)
   1.272 +                            {
   1.273 +                                Log.Verbose("BuildAndShowManager: Creating PEPMessage.");
   1.274 +
   1.275 +                                if (PEPMessage.Create(this._CurrentMailItem, out message) != Globals.ReturnStatus.Success)
   1.276 +                                {
   1.277 +                                    message = null;
   1.278 +                                    Log.Error("BuildAndShowManager: Error creating PEPMessage.");
   1.279 +                                }
   1.280 +                                else
   1.281 +                                {
   1.282 +                                    message.Rating = AdapterExtensions.ReevaluateMessageRating(message);
   1.283 +                                }
   1.284 +                            }
   1.285 +
   1.286 +                            // Get myself identiy if we don't have it yet
   1.287 +                            if (myself == null)
   1.288 +                            {
   1.289 +                                myself = this._CurrentMailItem.GetMyselfIdentity();
   1.290 +                            }
   1.291 +                        }
   1.292 +                        catch (Exception ex)
   1.293 +                        {
   1.294 +                            Log.Error("FormRegionPrivacyStatus.Message: Error converting message. " + ex.ToString());
   1.295 +                        }
   1.296 +                        finally
   1.297 +                        {
   1.298 +                            mirror = null;
   1.299 +                        }
   1.300 +                    }
   1.301 +                }
   1.302 +
   1.303 +                // Build dialog
   1.304 +                if (message != null)
   1.305 +                {
   1.306 +                    handshakeDialog = new HandshakeDialog(message, myself, this.IsDraft);
   1.307 +                    handshakeDialog.OnUpdateStatus += HandshakeDialog_Updated;
   1.308 +                    handshakeDialog.Closed += HandshakeDialog_Closed;
   1.309 +                    handshakeDialog.Show();
   1.310 +                }
   1.311 +                else
   1.312 +                {
   1.313 +                    throw new Exception("Could not build handshake dialog. Message is null.");
   1.314 +                }
   1.315 +            }
   1.316 +            catch (Exception ex)
   1.317 +            {
   1.318 +                Globals.StopAndSendCrashReport(ex);
   1.319 +            }
   1.320 +        }
   1.321 +
   1.322 +        /// <summary>
   1.323 +        /// Schedules for the pEp rating and UI (including displayed mirror) to be updated.
   1.324 +        /// This can be called many times with no issue as the update is only run every n milliseconds.
   1.325 +        /// </summary>
   1.326 +        public void RequestRatingAndUIUpdate()
   1.327 +        {
   1.328 +            if (this.isEnabled)
   1.329 +            {
   1.330 +                this.TimerRefresh.Enabled = true;
   1.331 +            }
   1.332 +        }
   1.333 +
   1.334 +        /// <summary>
   1.335 +        /// Immediately starts the update of UI rating based on the associated mail item.
   1.336 +        /// This will start decryption as necessary and also will update the displayed mirror.
   1.337 +        /// This method by-passes the refresh timer completely.
   1.338 +        /// WARNING: This method assumes the message is fully downloaded already.
   1.339 +        /// </summary>
   1.340 +        private void ImmediateRatingAndUIUpdate()
   1.341 +        {
   1.342 +            if ((this.isEnabled) &&
   1.343 +                (this.cryptableMailItem != null))
   1.344 +            {
   1.345 +                Log.Verbose("ImmediateRatingAndUIUpdate: Starting processing.");
   1.346 +
   1.347 +                // Start the rating calculation/decryption process
   1.348 +                this.cryptableMailItem.StartProcessing();
   1.349 +                this.processingOngoing = true;
   1.350 +            }
   1.351 +        }
   1.352 +
   1.353 +        /// <summary>
   1.354 +        /// Resets the Enabled status of this form region and recalculates the rating if necessary.
   1.355 +        /// </summary>
   1.356 +        /// <param name="enable">Whether to enable the form region.</param>
   1.357 +        public void UpdateFormRegion(bool enable)
   1.358 +        {
   1.359 +            this.SetIsEnabled(enable);
   1.360 +
   1.361 +            // Refresh the UI
   1.362 +            if (enable)
   1.363 +            {
   1.364 +                this.ResolveAllRecipients();
   1.365 +                this.RequestRatingAndUIUpdate();
   1.366 +            }
   1.367 +        }
   1.368 +
   1.369 +        /// <summary>
   1.370 +        /// Workaround method to update the current inspector window. This is done by moving the mail item
   1.371 +        /// to a temporary folder first and then back to the current folder. Both folders CANNOT be the same.
   1.372 +        /// As a fallback, the mail item stays in the temporary folder if moving back to the current folder
   1.373 +        /// fails.
   1.374 +        /// </summary>
   1.375 +        private void UpdateInspector()
   1.376 +        {
   1.377 +            Outlook.Application application = null;
   1.378 +            Outlook.Folder currentFolder = null;
   1.379 +            Outlook.Folder tempFolder = null;
   1.380 +            Outlook.Inspector currentInspector = null;
   1.381 +            Outlook.Inspector newInspector = null;
   1.382 +            Outlook.MailItem tempMailItem = null;
   1.383 +            Outlook.Store store = null;
   1.384 +            Outlook.MailItem omi = this.CurrentMailItem;
   1.385 +
   1.386 +            if (omi != null)
   1.387 +            {
   1.388 +                try
   1.389 +                {
   1.390 +                    application = omi.Application;
   1.391 +                    currentInspector = omi.GetInspector;
   1.392 +                    currentFolder = omi.Parent as Outlook.Folder;
   1.393 +
   1.394 +                    if ((currentInspector != null) &&
   1.395 +                        (application != null) &&
   1.396 +                        (currentFolder != null))
   1.397 +                    {
   1.398 +                        var left = currentInspector.Left;
   1.399 +                        var top = currentInspector.Top;
   1.400 +                        var width = currentInspector.Width;
   1.401 +                        var height = currentInspector.Height;
   1.402 +                        var windowState = currentInspector.WindowState;
   1.403 +
   1.404 +                        /* Check, if in trusted store. In that case, use the default drafts folder
   1.405 +                         * as temporary folder. If the store is untrusted, use the pEp drafts folder.
   1.406 +                         */
   1.407 +                        store = currentFolder.Store;
   1.408 +                        if (store?.GetIsSecureStorageEnabled() ?? false)
   1.409 +                        {
   1.410 +                            tempFolder = Globals.ThisAddIn.GetPEPStoreDraftsFolder();
   1.411 +                        }
   1.412 +                        else
   1.413 +                        {
   1.414 +                            tempFolder = store.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;
   1.415 +                        }
   1.416 +
   1.417 +                        if (tempFolder != null)
   1.418 +                        {
   1.419 +                            tempMailItem = omi.Move(tempFolder) as Outlook.MailItem;
   1.420 +
   1.421 +                            if (tempMailItem != null)
   1.422 +                            {
   1.423 +                                try
   1.424 +                                {
   1.425 +                                    omi = tempMailItem.Move(currentFolder) as Outlook.MailItem;
   1.426 +                                }
   1.427 +                                catch
   1.428 +                                {
   1.429 +                                    omi = tempMailItem.Copy();
   1.430 +                                }
   1.431 +
   1.432 +                                newInspector = application.Inspectors.Add(omi);
   1.433 +
   1.434 +                                if (windowState == Outlook.OlWindowState.olNormalWindow)
   1.435 +                                {
   1.436 +                                    newInspector.Left = left;
   1.437 +                                    newInspector.Top = top;
   1.438 +                                    newInspector.Width = width;
   1.439 +                                    newInspector.Height = height;
   1.440 +                                }
   1.441 +
   1.442 +                                newInspector.Display();
   1.443 +                                newInspector.WindowState = windowState;
   1.444 +
   1.445 +                                repeatProcessing = false;
   1.446 +                            }
   1.447 +                        }
   1.448 +                        else
   1.449 +                        {
   1.450 +                            Log.Error("UpdateInspector: Cannot get temporary folder.");
   1.451 +                        }
   1.452 +                    }
   1.453 +                    else
   1.454 +                    {
   1.455 +                        Log.Verbose("UpdateInspector: Error retrieving inspector window or application.");
   1.456 +                    }
   1.457 +                }
   1.458 +                catch (Exception ex)
   1.459 +                {
   1.460 +                    Log.Verbose("UpdateInspector: Error updating inspector window. " + ex.ToString());
   1.461 +                }
   1.462 +                finally
   1.463 +                {
   1.464 +                    application = null;
   1.465 +                    currentInspector = null;
   1.466 +                    newInspector = null;
   1.467 +                    omi = null;
   1.468 +                    tempMailItem = null;
   1.469 +                }
   1.470 +            }
   1.471 +        }
   1.472 +
   1.473 +        /// <summary>
   1.474 +        /// Clears the associated unencrypted preview and displays the given note (if any).
   1.475 +        /// </summary>
   1.476 +        /// <param name="note">The note to display.</param>
   1.477 +        private void SetNote(string note = null)
   1.478 +        {
   1.479 +            WindowFormRegionCollection formRegions = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveWindow()];
   1.480 +
   1.481 +            if ((formRegions != null) &&
   1.482 +                (string.IsNullOrEmpty(note) == false))
   1.483 +            {
   1.484 +                if ((formRegions.FormRegionPreviewUnencrypted != null) &&
   1.485 +                    (formRegions.FormRegionPreviewUnencrypted.Visible))
   1.486 +                {
   1.487 +                    formRegions.FormRegionPreviewUnencrypted.DisplayState.SetNote(note);
   1.488 +                }
   1.489 +            }
   1.490 +        }
   1.491 +
   1.492 +        /// <summary>
   1.493 +        /// Sets whether processing of the mail item is enabled.
   1.494 +        /// This should commonly be set from the .GetIsPEPEnabled() value.
   1.495 +        /// </summary>
   1.496 +        private void SetIsEnabled(bool enabled)
   1.497 +        {
   1.498 +            PEPIdentity currIdent;
   1.499 +            Globals.ReturnStatus sts;
   1.500 +            Outlook.Recipient currUser = null;
   1.501 +            Outlook.Account currAccount = null;
   1.502 +            Outlook.Account sendingAccount = null;
   1.503 +            Outlook.NameSpace ns = null;
   1.504 +
   1.505 +            this.isEnabled = enabled;
   1.506 +
   1.507 +            if (enabled)
   1.508 +            {
   1.509 +                // Do not allow initialization more than once
   1.510 +                if (this.isStarted == false)
   1.511 +                {
   1.512 +                    /* It's possible for new draft MailItems to be created outside the context of an account.
   1.513 +                     * In this situation the SendUsingAccount will always be null which of course breaks several pEp operations.
   1.514 +                     * The operations themselves cannot make the assumption about what account information to use.
   1.515 +                     * Therefore, the situation is detected here and for draft mail items a null SendUsingAccount will be 
   1.516 +                     * set with the session's default account.
   1.517 +                     */
   1.518 +                    try
   1.519 +                    {
   1.520 +                        ns = Globals.ThisAddIn.Application.Session;
   1.521 +
   1.522 +                        if (this.IsDraft)
   1.523 +                        {
   1.524 +                            sendingAccount = this._CurrentMailItem.SendUsingAccount;
   1.525 +                            currUser = ns.CurrentUser;
   1.526 +
   1.527 +                            if (sendingAccount == null)
   1.528 +                            {
   1.529 +                                sts = PEPIdentity.Create(currUser, out currIdent);
   1.530 +
   1.531 +                                if (sts == Globals.ReturnStatus.Success)
   1.532 +                                {
   1.533 +                                    sendingAccount = AccountExtensions.GetDefaultAccount(Outlook.OlDefaultFolders.olFolderDrafts);
   1.534 +                                    if (sendingAccount != null)
   1.535 +                                    {
   1.536 +                                        this._CurrentMailItem.SendUsingAccount = currAccount;
   1.537 +                                    }
   1.538 +                                }
   1.539 +                            }
   1.540 +
   1.541 +                            // Check if account is already registered in pEp list and add it if necessary
   1.542 +                            var acctSettings = Globals.ThisAddIn.Settings.GetAccountSettings(sendingAccount?.SmtpAddress);
   1.543 +                            if (acctSettings == null)
   1.544 +                            {
   1.545 +                                Log.Verbose("SetIsEnabled: New account detected. Creating pEp settings.");
   1.546 +
   1.547 +                                // Create pEp settings for the new account
   1.548 +                                acctSettings = sendingAccount.CreatePEPSettings();
   1.549 +
   1.550 +                                // Add account to list
   1.551 +                                Globals.ThisAddIn.Settings.AccountsAddedWhileRunningList.Add(acctSettings?.SmtpAddress);
   1.552 +                                Log.Verbose("SetIsEnabled: New account registered in pEp settings.");
   1.553 +
   1.554 +                                // Generate key
   1.555 +                                Globals.ThisAddIn.RegisterMyself(acctSettings);
   1.556 +                                Log.Verbose("SetIsEnabled: Myself registered.");
   1.557 +
   1.558 +                                // Set rules and view filters
   1.559 +                                Globals.ThisAddIn.SetRulesAndViewFilters(sendingAccount);
   1.560 +                            }
   1.561 +                        }
   1.562 +                    }
   1.563 +                    catch (Exception ex)
   1.564 +                    {
   1.565 +                        Log.Error("SetIsEnabled: Error occured. " + ex.ToString());
   1.566 +                    }
   1.567 +                    finally
   1.568 +                    {
   1.569 +                        currAccount = null;
   1.570 +                        currUser = null;
   1.571 +                        ns = null;
   1.572 +                        sendingAccount = null;
   1.573 +                    }
   1.574 +
   1.575 +                    // Connect refresh timer
   1.576 +                    this.TimerRefresh.Tick += TimerRefresh_Tick;
   1.577 +                    this.isStarted = true;
   1.578 +                }
   1.579 +            }
   1.580 +            else
   1.581 +            {
   1.582 +                // Stop and disconnect the refresh timer
   1.583 +                this.TimerRefresh.Stop();
   1.584 +                this.TimerRefresh.Enabled = false;
   1.585 +                this.TimerRefresh.Tick -= TimerRefresh_Tick;
   1.586 +
   1.587 +                this.isStarted = false;
   1.588 +            }
   1.589 +        }
   1.590 +
   1.591 +        /// <summary>
   1.592 +        /// Resolves all recipients of the Outlook mail item.
   1.593 +        /// </summary>
   1.594 +        private void ResolveAllRecipients()
   1.595 +        {
   1.596 +            if ((this.isEnabled) &&
   1.597 +                (this.cryptableMailItem != null))
   1.598 +            {
   1.599 +                /*
   1.600 +                 * Note: The PropertyChanged changed event must be disconnected before trying to resolve.
   1.601 +                 * This is because the resolve process can modify the contents of the mail item which triggers an event.
   1.602 +                 * The PropertyChanged event would then trigger a UI refresh cycle. However, because the GetManagerState itself 
   1.603 +                 * is called within the UI refresh, an infinite loop could occur trying to resolve a recipient that
   1.604 +                 * cannot be resolved(no address).
   1.605 +                 */
   1.606 +                try
   1.607 +                {
   1.608 +                    this.cryptableMailItem.PropertyChanged -= MailItem_PropertyChanged;
   1.609 +                    this.cryptableMailItem.ResolveAllRecipients();
   1.610 +                    this.cryptableMailItem.PropertyChanged += MailItem_PropertyChanged;
   1.611 +                }
   1.612 +                catch (Exception ex)
   1.613 +                {
   1.614 +                    Log.Error("Error resolving recipients. " + ex.ToString());
   1.615 +                }
   1.616 +            }
   1.617 +        }
   1.618 +        #endregion
   1.619 +
   1.620 +        #region Event Handling
   1.621 +        /**************************************************************
   1.622 +         * 
   1.623 +         * Event Handling
   1.624 +         * 
   1.625 +         *************************************************************/
   1.626 +
   1.627 +        protected void InitializeMailItem(bool isInlineResponse = false)
   1.628 +        {
   1.629 +            bool enableFormRegion = false;
   1.630 +            bool cancelOpenEvent = false;
   1.631 +            bool isSecureAttachedMail = false;
   1.632 +            string messageId = null;
   1.633 +
   1.634 +            try
   1.635 +            {      
   1.636 +                // Check if draft
   1.637 +                this.IsDraft = this._CurrentMailItem.GetIsDraft();
   1.638 +
   1.639 +                /* Set immediately a provisional rating in order to have a less flickery
   1.640 +                 * UI experience.
   1.641 +                 * The provisional rating is either a stored rating or, in case we have a
   1.642 +                 * reply message, the rating of the original (the item we reply to).
   1.643 +                 * This provisional rating will be replace with the real one once the full
   1.644 +                 * processing is complete.
   1.645 +                 */
   1.646 +                pEpRating provisionalRating = pEpRating.pEpRatingUndefined;
   1.647 +
   1.648 +                // Try to get an original rating (in case of reply messages)
   1.649 +                if ((this.IsDraft) &&
   1.650 +                    (this._CurrentMailItem?.Recipients?.Count > 0))
   1.651 +                {
   1.652 +                    string originalRatingString = this._CurrentMailItem.GetUserProperty(CryptableMailItem.USER_PROPERTY_KEY_ORIGINAL_RATING) as string;
   1.653 +
   1.654 +                    // If we have an original rating, parse it and set it.
   1.655 +                    if (string.IsNullOrEmpty(originalRatingString) == false)
   1.656 +                    {
   1.657 +                        provisionalRating = AdapterExtensions.ParseRatingString(originalRatingString);
   1.658 +                    }
   1.659 +                }
   1.660 +                else
   1.661 +                {
   1.662 +                    // Try to get rating from db
   1.663 +                    provisionalRating = PEPDatabase.GetRating(this._CurrentMailItem.EntryID);
   1.664 +
   1.665 +                    // If there is no rating in the db, use stored or default rating
   1.666 +                    if (provisionalRating == pEpRating.pEpRatingUndefined)
   1.667 +                    {
   1.668 +                        provisionalRating = this._CurrentMailItem.GetStoredRating() ?? pEpRating.pEpRatingUndefined;
   1.669 +                    }
   1.670 +                }
   1.671 +
   1.672 +                // Only set rating if one has been retrieved
   1.673 +                if (provisionalRating != pEpRating.pEpRatingUndefined)
   1.674 +                {
   1.675 +                    this.SetRating(provisionalRating);
   1.676 +                    Log.Verbose("FormRegionPrivacyStatus_FormRegionShowing: Provisional rating {0} shown.", Enum.GetName(typeof(pEpRating), provisionalRating));
   1.677 +                }
   1.678 +
   1.679 +
   1.680 +                // Do not process S/MIME messages
   1.681 +                if (this._CurrentMailItem.GetIsSMIMEEnabled())
   1.682 +                {
   1.683 +                    Log.Verbose("FormRegionPrivacyStatus_FormRegionShowing: S/MIME message detected. Won't be processed.");
   1.684 +
   1.685 +                    // Set unencrypted rating
   1.686 +                    this.SetRating(pEpRating.pEpRatingUnencrypted);
   1.687 +
   1.688 +                    // Set icon(s) if necessary     
   1.689 +                    if ((IsDraft == false) &&
   1.690 +                        (this._CurrentMailItem.SetEncryptionIcons()))
   1.691 +                    {
   1.692 +                        try
   1.693 +                        {
   1.694 +                            this._CurrentMailItem.Save();
   1.695 +                        }
   1.696 +                        catch (Exception ex)
   1.697 +                        {
   1.698 +                            Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Error saving message after changing icon. " + ex.ToString());
   1.699 +                        }
   1.700 +                    }
   1.701 +
   1.702 +                    return;
   1.703 +                }
   1.704 +
   1.705 +                /* Check if item is attached mail. For performance reasons,
   1.706 +                 * only do the whole check if an item has been loaded to the
   1.707 +                 * cache of attached mails and if item might be secure.
   1.708 +                 */
   1.709 +                if ((PEPAttachment.AttachedMailsCache.Count > 0) &&
   1.710 +                    (this._CurrentMailItem.Attachments?.Count == 2))
   1.711 +                {
   1.712 +                    try
   1.713 +                    {
   1.714 +                        // Check if mail item is an attached mail
   1.715 +                        if (this._CurrentMailItem.GetIsAttachedMail(out messageId))
   1.716 +                        {
   1.717 +                            Outlook.MailItem mirror = null;
   1.718 +                            PEPMessage pEpMessage;
   1.719 +
   1.720 +                            // Try to get the mirror
   1.721 +                            mirror = this._CurrentMailItem.GetMirror(messageId);
   1.722 +
   1.723 +                            // If mirror was not found, decrypt and create mirror
   1.724 +                            if (mirror != null)
   1.725 +                            {
   1.726 +                                isSecureAttachedMail = true;
   1.727 +                            }
   1.728 +                            else
   1.729 +                            {
   1.730 +                                if ((PEPMessage.Create(this._CurrentMailItem, out pEpMessage) == Globals.ReturnStatus.Success) &&
   1.731 +                                    (pEpMessage.IsSecure))
   1.732 +                                {
   1.733 +                                    PEPMessage decryptedMessage;
   1.734 +                                    MsgProcessor msgProcessor = new MsgProcessor();
   1.735 +                                    if (msgProcessor.Decrypt(pEpMessage, out decryptedMessage))
   1.736 +                                    {
   1.737 +                                        isSecureAttachedMail = true;
   1.738 +                                        mirror = this._CurrentMailItem.CreateMirrorOMI(messageId);
   1.739 +                                        decryptedMessage.ApplyTo(mirror, true, false);
   1.740 +                                        mirror?.Save();
   1.741 +                                    }
   1.742 +                                    else
   1.743 +                                    {
   1.744 +                                        Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Decryption of attached mail was not successful.");
   1.745 +                                    }
   1.746 +                                }
   1.747 +                            }
   1.748 +
   1.749 +                            // Check if attachment is being opened or if only the preview is needed
   1.750 +                            if (CryptableMailItem.PreviewAttachedMailId?.Equals(messageId) != true)
   1.751 +                            {
   1.752 +                                // Display mirror and cancel opening of original
   1.753 +                                cancelOpenEvent = true;
   1.754 +                                mirror?.Display();
   1.755 +                            }
   1.756 +
   1.757 +                            // Not needed anymore after this point
   1.758 +                            CryptableMailItem.PreviewAttachedMailId = null;
   1.759 +                        }
   1.760 +                    }
   1.761 +                    catch (Exception ex)
   1.762 +                    {
   1.763 +                        messageId = null;
   1.764 +                        Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Error checking for attached mail. " + ex.ToString());
   1.765 +                    }
   1.766 +                }
   1.767 +
   1.768 +                this.cryptableMailItem = new CryptableMailItem(this._CurrentMailItem, provisionalRating);
   1.769 +
   1.770 +                // Set inline response property
   1.771 +                this.cryptableMailItem.IsInlineResponse = isInlineResponse;
   1.772 +
   1.773 +                // Set properties for encrypted attached mail
   1.774 +                if (isSecureAttachedMail)
   1.775 +                {
   1.776 +                    this.cryptableMailItem.MessageId = messageId;
   1.777 +                    this.cryptableMailItem.IsSecureAttachedMail = true;
   1.778 +                }
   1.779 +
   1.780 +                // Connect cryptable mail item events
   1.781 +                if (this.cryptableMailItem != null)
   1.782 +                {
   1.783 +                    // If we don't open the original, set property and return
   1.784 +                    if (cancelOpenEvent)
   1.785 +                    {
   1.786 +                        this.cryptableMailItem.Open += MailItem_Open;
   1.787 +                        this.cryptableMailItem.CancelOpen = true;
   1.788 +                        return;
   1.789 +                    }
   1.790 +                    else
   1.791 +                    {
   1.792 +                        try
   1.793 +                        {
   1.794 +                            this.cryptableMailItem.PropertyChanged += MailItem_PropertyChanged;
   1.795 +                            this.cryptableMailItem.ProcessingCompleted += MailItem_ProcessingCompleted;
   1.796 +                            this.cryptableMailItem.GetMirrorCompleted += MailItem_GetMirrorCompleted;
   1.797 +                            this.cryptableMailItem.Send += MailItem_Send;
   1.798 +
   1.799 +                            if (this.cryptableMailItem.IsSecurelyStored)
   1.800 +                            {
   1.801 +                                this.cryptableMailItem.Open += MailItem_Open;
   1.802 +                            }
   1.803 +                        }
   1.804 +                        catch (Exception ex)
   1.805 +                        {
   1.806 +                            Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Error occured. " + ex.ToString());
   1.807 +                        }
   1.808 +
   1.809 +                        if (this._CurrentMailItem.GetIsPEPEnabled())
   1.810 +                        {
   1.811 +                            // If pEp is enabled, show the form region
   1.812 +                            enableFormRegion = true;
   1.813 +                        }
   1.814 +                        else
   1.815 +                        {
   1.816 +                            /* If pEp is disabled, process item and show form region in the following cases:
   1.817 +                             * 1. Incoming items: if decrypt always option is set
   1.818 +                             * 2. Outgoing items: if EnableProtection option is set
   1.819 +                             *                    Note: if this property isn't set, subscribe to originally 
   1.820 +                             *                          encrypted status update event handler in case the 
   1.821 +                             *                          current code runs before CryptableMailItem.MailItem_Reply
   1.822 +                             *                          or CryptableMailItem.MailItem_Forward.
   1.823 +                             */
   1.824 +                            if (this.IsDraft)
   1.825 +                            {
   1.826 +                                enableFormRegion = true;
   1.827 +                                this.cryptableMailItem.OriginallyEncryptedStatusUpdated += CryptableMailItem_OriginallyEncryptedStatusUpdated;
   1.828 +                            }
   1.829 +                            else
   1.830 +                            {
   1.831 +                                enableFormRegion = this._CurrentMailItem.GetIsDecryptAlwaysEnabled();
   1.832 +                            }
   1.833 +                        }
   1.834 +                    }
   1.835 +                }
   1.836 +
   1.837 +                // Update pEp enabled status
   1.838 +                this.SetIsEnabled(enableFormRegion);
   1.839 +
   1.840 +                if (this.isEnabled)
   1.841 +                {
   1.842 +                    // If forcefully protected, run dedicated decryption
   1.843 +                    if (this._CurrentMailItem.GetIsForcefullyProtected())
   1.844 +                    {
   1.845 +                        FPPMessage fppMessage = new FPPMessage(this._CurrentMailItem);
   1.846 +                        if ((fppMessage?.GetMessageType() != null) ||
   1.847 +                            (fppMessage?.CurrentMessage?.IsSecure == true))
   1.848 +                        {
   1.849 +                            fppMessage.ProcessIncoming(true);
   1.850 +                        }
   1.851 +                        else
   1.852 +                        {
   1.853 +                            this.TimerRefresh_Tick(null, new EventArgs());
   1.854 +                        }
   1.855 +                    }
   1.856 +                    else
   1.857 +                    {
   1.858 +                        // Call the timer tick method manually to refresh data with no delay
   1.859 +                        this.TimerRefresh_Tick(null, new EventArgs());
   1.860 +                    }
   1.861 +                }
   1.862 +            }
   1.863 +            catch (Exception e)
   1.864 +            {
   1.865 +                Log.Error("Window_SelectionChange: Error. " + e.Message);
   1.866 +            }
   1.867 +        }
   1.868 +
   1.869 +        /// <summary>
   1.870 +        /// Event handler for when the form region is closed.
   1.871 +        /// </summary>
   1.872 +        protected void FormRegionPrivacyStatus_FormRegionClosed(object sender, EventArgs e)
   1.873 +        {
   1.874 +            // Disconnect cryptable mail item
   1.875 +            if (this.cryptableMailItem != null)
   1.876 +            {
   1.877 +                try
   1.878 +                {
   1.879 +                    this.cryptableMailItem.PropertyChanged -= MailItem_PropertyChanged;
   1.880 +                    this.cryptableMailItem.ProcessingCompleted -= MailItem_ProcessingCompleted;
   1.881 +                    this.cryptableMailItem.GetMirrorCompleted -= MailItem_GetMirrorCompleted;
   1.882 +                    this.cryptableMailItem.Open -= MailItem_Open;
   1.883 +                    this.cryptableMailItem.Send -= MailItem_Send;
   1.884 +                    this.cryptableMailItem.OriginallyEncryptedStatusUpdated -= CryptableMailItem_OriginallyEncryptedStatusUpdated;
   1.885 +                }
   1.886 +                catch { }
   1.887 +
   1.888 +                this.cryptableMailItem.Dispose();
   1.889 +                this.cryptableMailItem = null;
   1.890 +            }
   1.891 +
   1.892 +            // Disconnect other
   1.893 +            this.SetIsEnabled(false);
   1.894 +        }
   1.895 +
   1.896 +        /// <summary>
   1.897 +        /// Event handler for when the processing is completed in the associated mail item.
   1.898 +        /// This will then update the form region UI and the privacy status window as needed.
   1.899 +        /// </summary>
   1.900 +        private void MailItem_ProcessingCompleted(object sender, MsgProcessor.ProcessingCompletedEventArgs e)
   1.901 +        {
   1.902 +            Log.Verbose("MailItem_ProcessingComplete: Decryption completed.");
   1.903 +
   1.904 +            try
   1.905 +            {
   1.906 +                // Marshal code back to UI thread as necessary
   1.907 +                KeySyncWizard.Wizard.Dispatcher.Invoke(new Action(() =>
   1.908 +                {
   1.909 +                    if (this.isEnabled)
   1.910 +                    {
   1.911 +                        try
   1.912 +                        {
   1.913 +                            this.SetRating(e.ProcessedRating);
   1.914 +
   1.915 +                            // Set MAPI properties if needed
   1.916 +                            if (e.PropertiesToSet?.Count > 0)
   1.917 +                            {
   1.918 +                                this._CurrentMailItem?.SetMAPIProperties(e.PropertiesToSet);
   1.919 +                            }
   1.920 +                            Log.Verbose("MailItem_ProcessingComplete: Status bar updated with rating " + Enum.GetName(typeof(pEpRating), e.ProcessedRating));
   1.921 +                        }
   1.922 +                        catch (Exception ex)
   1.923 +                        {
   1.924 +                            Log.Verbose("MailItem_ProcessingComplete: Error. " + ex.ToString());
   1.925 +                        }
   1.926 +
   1.927 +                        if (repeatProcessing &&
   1.928 +                            (repeatCounter++ < maxRepeatCount))
   1.929 +                        {
   1.930 +                            repeatProcessing = false;
   1.931 +                            this.RequestRatingAndUIUpdate();
   1.932 +                        }
   1.933 +                        else
   1.934 +                        {
   1.935 +                            /* Check if the mail item is in Outbox and update the inspector window if possible.
   1.936 +                             * This is the case when a submitted, but not yet sent email is opened again when working 
   1.937 +                             * offline or without internet connection. Without this update, Outlook removes the message class 
   1.938 +                             * "IPM.Note.SMIME.MultipartSigned" at the next send event and the message gets invalid and can't be
   1.939 +                             * opened again (i.e. is lost).
   1.940 +                             */
   1.941 +                            try
   1.942 +                            {
   1.943 +                                if ((this._CurrentMailItem?.GetIsSubmitted() == true) &&
   1.944 +                                    (this.IsDraft))
   1.945 +                                {
   1.946 +                                    UpdateInspector();
   1.947 +                                }
   1.948 +                            }
   1.949 +                            catch (Exception ex)
   1.950 +                            {
   1.951 +                                Log.Verbose("MailItem_ProcessingComplete: Error while checking if mail item is in outbox or updating inspector. " + ex.Message);
   1.952 +                            }
   1.953 +
   1.954 +                            /* Create the unencrypted preview if the mail item is encrypted and
   1.955 +                             * it is in an encrypted (untrusted) store
   1.956 +                             * 
   1.957 +                             * This is done here because FormRegionPrivacyStatus has the cryptable mail item and
   1.958 +                             * it also is initialized after FormRegionPreviewUnencrypted.
   1.959 +                             */
   1.960 +                            try
   1.961 +                            {
   1.962 +                                if (this.cryptableMailItem.IsSecurelyStored || this.cryptableMailItem.IsSecureAttachedMail)
   1.963 +                                {
   1.964 +                                    Log.Verbose("MailItem_ProcessingComplete: Starting mirror location.");
   1.965 +                                    this.cryptableMailItem.StartGetMirror(this.cryptableMailItem.MessageId);
   1.966 +                                }
   1.967 +                                else
   1.968 +                                {
   1.969 +                                    this.SetNote();
   1.970 +                                }
   1.971 +                            }
   1.972 +                            catch (Exception ex)
   1.973 +                            {
   1.974 +                                // Error is possible in some situations where the mail item was deleted or moved while decryption was ongoing.
   1.975 +                                // While rare, just log the issue and stop the process
   1.976 +                                Log.Warning("MailItem_ProcessingComplete: Failed to start mirror location, " + ex.ToString());
   1.977 +                            }
   1.978 +
   1.979 +                            /* OUT-470: Workaround until this is implemented in the engine:
   1.980 +                             * Only enable Force Protection if all recipients are grey
   1.981 +                             */
   1.982 +                            if (this.IsDraft)
   1.983 +                            {
   1.984 +                                bool disableForceProtection = false;
   1.985 +                                Outlook.Recipients recipients = null;
   1.986 +                                Outlook.Recipient recipient = null;
   1.987 +                                PEPIdentity pEpIdentity = null;
   1.988 +
   1.989 +                                try
   1.990 +                                {
   1.991 +                                    recipients = this._CurrentMailItem?.Recipients;
   1.992 +                                    if (recipients?.Count > 0)
   1.993 +                                    {
   1.994 +                                        for (int i = 1; i <= recipients.Count; i++)
   1.995 +                                        {
   1.996 +                                            recipient = recipients[i];
   1.997 +                                            if ((PEPIdentity.Create(recipient, out pEpIdentity, false) == Globals.ReturnStatus.Success) &&
   1.998 +                                                ((PEPIdentity.GetIsOwnIdentity(pEpIdentity.Address) ||
   1.999 +                                                 (ThisAddIn.PEPEngine.IdentityRating(pEpIdentity.ToCOMType()) >= pEpRating.pEpRatingReliable))))
  1.1000 +                                            {
  1.1001 +                                                disableForceProtection = true;
  1.1002 +                                                Log.Verbose("ToggleButtonForceProtection_GetEnabled: Secure recipient found. Disabling force protection.");
  1.1003 +                                                break;
  1.1004 +                                            }
  1.1005 +                                        }
  1.1006 +                                    }
  1.1007 +                                    else
  1.1008 +                                    {
  1.1009 +                                        // If there aren't any recipients (anymore), reset values
  1.1010 +                                        this.DisableForceProtection = false;
  1.1011 +                                        this.ForceProtection = false;
  1.1012 +                                        this.NeverUnsecure = false;
  1.1013 +                                        this.ForceUnencrypted = false;
  1.1014 +                                    }
  1.1015 +                                }
  1.1016 +                                catch (Exception ex)
  1.1017 +                                {
  1.1018 +                                    Log.Error("ToggleButtonForceProtection_GetEnabled: Error occured. " + ex.ToString());
  1.1019 +                                }
  1.1020 +                                finally
  1.1021 +                                {
  1.1022 +                                    recipient = null;
  1.1023 +                                    recipients = null;
  1.1024 +                                }
  1.1025 +
  1.1026 +                                this.DisableForceProtection = disableForceProtection;
  1.1027 +                            }
  1.1028 +                        }
  1.1029 +                    }
  1.1030 +                }));
  1.1031 +            }
  1.1032 +            catch (Exception ex)
  1.1033 +            {
  1.1034 +                Log.Error("MailItem_ProcessingComplete: Error setting UI state, " + ex.ToString());
  1.1035 +            }
  1.1036 +
  1.1037 +            this.processingOngoing = false;
  1.1038 +        }
  1.1039 +
  1.1040 +        /// <summary>
  1.1041 +        /// Event handler for when the get mirror locating process is complete for the associated mail item.
  1.1042 +        /// This will then update the unencrypted preview in the UI.
  1.1043 +        /// </summary>
  1.1044 +        private void MailItem_GetMirrorCompleted(object sender, CryptableMailItem.GetMirrorCompletedEventArgs e)
  1.1045 +        {
  1.1046 +            try
  1.1047 +            {
  1.1048 +                // Marshal code back to UI thread as necessary
  1.1049 +                KeySyncWizard.Wizard.Dispatcher.Invoke(new Action(() =>
  1.1050 +                {
  1.1051 +                    if (this.isEnabled)
  1.1052 +                    {
  1.1053 +                        WindowFormRegionCollection formRegions = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveWindow()];
  1.1054 +
  1.1055 +                        // If the message was forcefully protected, there is no mirror and we show the actual message
  1.1056 +                        if ((e.Mirror == null) &&
  1.1057 +                            (this._CurrentMailItem?.GetIsForcefullyProtected() == true))
  1.1058 +                        {
  1.1059 +                            PEPMessage mirror = null;
  1.1060 +                            if (PEPMessage.Create(this._CurrentMailItem, out mirror) == Globals.ReturnStatus.Success)
  1.1061 +                            {
  1.1062 +                                e.Mirror = mirror;
  1.1063 +                            }
  1.1064 +                        }
  1.1065 +
  1.1066 +                        if ((e.Mirror == null) &&
  1.1067 +                            (this.cryptableMailItem.LastProcessedStatus == Globals.ReturnStatus.Failure))
  1.1068 +                        {
  1.1069 +                            this.SetNote(Properties.Resources.Message_OpenError);
  1.1070 +                            Log.Verbose("MailItem_GetMirrorComplete: Cannot display mirror, failure during decryption.");
  1.1071 +                        }
  1.1072 +                        else if ((e.Mirror == null) &&
  1.1073 +                                 (this.cryptableMailItem.LastProcessedStatus == Globals.ReturnStatus.FailureNoConnection))
  1.1074 +                        {
  1.1075 +                            this.SetNote(Properties.Resources.Message_DecryptionNoConnection);
  1.1076 +                            Log.Verbose("MailItem_GetMirrorComplete: Cannot display mirror, connection failure during decryption.");
  1.1077 +                        }
  1.1078 +                        else
  1.1079 +                        {
  1.1080 +                            if (formRegions != null)
  1.1081 +                            {
  1.1082 +                                if ((formRegions.FormRegionPreviewUnencrypted != null) &&
  1.1083 +                                    (formRegions.FormRegionPreviewUnencrypted.Visible))
  1.1084 +                                {
  1.1085 +                                    formRegions.FormRegionPreviewUnencrypted.DisplayState.OriginalEntryId = this._CurrentMailItem?.EntryID;
  1.1086 +                                    formRegions.FormRegionPreviewUnencrypted.DisplayState.SetMessage(e.Mirror);
  1.1087 +                                }
  1.1088 +
  1.1089 +                                Log.Verbose("MailItem_GetMirrorComplete: Mirror found and displayed.");
  1.1090 +                            }
  1.1091 +                        }
  1.1092 +
  1.1093 +                        // Display the mirror if necessary
  1.1094 +                        if ((this.cryptableMailItem != null) &&
  1.1095 +                            (this.displayMirrorRequested))
  1.1096 +                        {
  1.1097 +                            this.cryptableMailItem.DisplayMirror();
  1.1098 +                            this.displayMirrorRequested = false;
  1.1099 +                        }
  1.1100 +                    }
  1.1101 +                }));
  1.1102 +            }
  1.1103 +            catch (Exception ex)
  1.1104 +            {
  1.1105 +                Log.Error("MailItem_GetMirrorComplete: Error displaying preview, " + ex.ToString());
  1.1106 +            }
  1.1107 +        }
  1.1108 +
  1.1109 +        /// <summary>
  1.1110 +        /// Event handler for the mail item originally encrypted status updated.
  1.1111 +        /// This event is fired after the status has been updated with parent information following a
  1.1112 +        /// forward or reply mail item event (on a different, likely parent, mail item).
  1.1113 +        /// </summary>
  1.1114 +        protected void CryptableMailItem_OriginallyEncryptedStatusUpdated(object sender, EventArgs e)
  1.1115 +        {
  1.1116 +            // Process the mail item now that the cache is updated
  1.1117 +            if (this.cryptableMailItem.IsOriginallyEncrypted)
  1.1118 +            {
  1.1119 +                this.cryptableMailItem.StartProcessing();
  1.1120 +            }
  1.1121 +        }
  1.1122 +
  1.1123 +        /// <summary>
  1.1124 +        /// Event handler for when a mail item is being opened in an inspector.
  1.1125 +        /// See: https://msdn.microsoft.com/en-us/library/office/ff865989.aspx
  1.1126 +        /// </summary>
  1.1127 +        /// <param name="cancel">Whether to cancel the event: Value is False when the event occurs. 
  1.1128 +        /// If the event procedure sets this argument to True, the open operation is not completed 
  1.1129 +        /// and the inspector is not displayed.</param>
  1.1130 +        protected void MailItem_Open(ref bool cancel)
  1.1131 +        {
  1.1132 +            bool result;
  1.1133 +
  1.1134 +            if ((this.isEnabled) &&
  1.1135 +                (this.cryptableMailItem != null))
  1.1136 +            {
  1.1137 +                // If cryptable mail item is not to be opened, cancel opening
  1.1138 +                if (this.cryptableMailItem.CancelOpen)
  1.1139 +                {
  1.1140 +                    cancel = true;
  1.1141 +                }
  1.1142 +                else if ((this.cryptableMailItem.IsSecurelyStored) &&
  1.1143 +                         (this.cryptableMailItem.IsIncoming || this.cryptableMailItem.IsOriginallyEncrypted || !this.cryptableMailItem.IsDraft))
  1.1144 +                {
  1.1145 +                    // Try to open the mirror
  1.1146 +                    result = this.cryptableMailItem.DisplayMirror();
  1.1147 +
  1.1148 +                    if (result == false)
  1.1149 +                    {
  1.1150 +                        // Set flag to open after decryption/mirror location
  1.1151 +                        this.displayMirrorRequested = true;
  1.1152 +                    }
  1.1153 +
  1.1154 +                    // Always cancel opening the original
  1.1155 +                    cancel = true;
  1.1156 +                }
  1.1157 +            }
  1.1158 +        }
  1.1159 +
  1.1160 +        /// <summary>
  1.1161 +        /// Event handler for when a mail item is sent.
  1.1162 +        /// See: https://msdn.microsoft.com/en-us/library/office/ff865379.aspx
  1.1163 +        /// </summary>
  1.1164 +        /// <param name="cancel">Whether to cancel the event: Value is False when the event occurs. 
  1.1165 +        /// If the event procedure sets this argument to True, the send operation is not completed 
  1.1166 +        /// and the inspector is left open.</param>
  1.1167 +        protected void MailItem_Send(ref bool cancel)
  1.1168 +        {
  1.1169 +            DialogResult result;
  1.1170 +
  1.1171 +            if (this.isEnabled)
  1.1172 +            {
  1.1173 +                if ((this.cryptableMailItem.IsBeingProcessed) ||
  1.1174 +                    (this.processingOngoing))
  1.1175 +                {
  1.1176 +                    Log.Verbose("MailItem_Send cancelled. Mail item still being processed.");
  1.1177 +                    cancel = true;
  1.1178 +                    return;
  1.1179 +                }
  1.1180 +
  1.1181 +                // Show warning message if needed
  1.1182 +                if ((Globals.ThisAddIn.Settings.IsSecurityLossWarningEnabled) &&
  1.1183 +                    (this.Rating < pEpRating.pEpRatingUnreliable) &&
  1.1184 +                    (this.cryptableMailItem.IsOriginallyEncrypted))
  1.1185 +                {
  1.1186 +
  1.1187 +#if READER_RELEASE_MODE
  1.1188 +                    FormReaderSplash warningMessage = new FormReaderSplash(true);
  1.1189 +                    result = warningMessage.ShowDialog();
  1.1190 +
  1.1191 +                    if (result != DialogResult.OK)
  1.1192 +                    {
  1.1193 +                        // Cancel sending
  1.1194 +                        cancel = true;
  1.1195 +                    }
  1.1196 +#else
  1.1197 +                    result = MessageBox.Show(Properties.Resources.Message_WarningSecurityLoss,
  1.1198 +                                             Properties.Resources.Message_TitleConfirmOperation,
  1.1199 +                                             MessageBoxButtons.YesNo,
  1.1200 +                                             MessageBoxIcon.Warning);
  1.1201 +
  1.1202 +                    if (result == DialogResult.No)
  1.1203 +                    {
  1.1204 +                        // Cancel sending
  1.1205 +                        cancel = true;
  1.1206 +                    }
  1.1207 +#endif
  1.1208 +                }
  1.1209 +
  1.1210 +                if (cancel == false)
  1.1211 +                {
  1.1212 +                    // Set pEp options if needed
  1.1213 +                    if ((this.ForceProtection) &&
  1.1214 +                        (this.DisableForceProtection == false))
  1.1215 +                    {
  1.1216 +                        this._CurrentMailItem?.SetPEPProperty(MailItemExtensions.PEPProperty.ForceProtection, Guid.NewGuid().ToString());
  1.1217 +                    }
  1.1218 +                    else if (this.ForceUnencrypted)
  1.1219 +                    {
  1.1220 +                        this._CurrentMailItem?.SetPEPProperty(MailItemExtensions.PEPProperty.ForceUnencrypted, true);
  1.1221 +                    }
  1.1222 +
  1.1223 +                    if (this.NeverUnsecure)
  1.1224 +                    {
  1.1225 +                        this._CurrentMailItem?.SetPEPProperty(MailItemExtensions.PEPProperty.NeverUnsecure, true);
  1.1226 +                    }
  1.1227 +
  1.1228 +                    // Stop and disconnect the refresh timer
  1.1229 +                    // This is necessary so an ongoing refresh doesn't try to access a mail item as it's being moved
  1.1230 +                    this.TimerRefresh.Stop();
  1.1231 +                    this.TimerRefresh.Enabled = false;
  1.1232 +                    this.TimerRefresh.Tick -= TimerRefresh_Tick;
  1.1233 +                }
  1.1234 +            }
  1.1235 +        }
  1.1236 +
  1.1237 +        /// <summary>
  1.1238 +        /// Event handler for when a mail item property is changed.
  1.1239 +        /// See: https://msdn.microsoft.com/en-us/library/office/ff866739.aspx
  1.1240 +        /// </summary>
  1.1241 +        /// <param name="propertyName">The name of the property that was changed.</param>
  1.1242 +        protected void MailItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
  1.1243 +        {
  1.1244 +            switch (e.PropertyName.ToUpperInvariant())
  1.1245 +            {
  1.1246 +                case "BCC":
  1.1247 +                    {
  1.1248 +                        // Outlook always fires Bcc, Cc and To together so only "TO" is used
  1.1249 +                        break;
  1.1250 +                    }
  1.1251 +                case "CC":
  1.1252 +                    {
  1.1253 +                        // Outlook always fires Bcc, Cc and To together so only "TO" is used
  1.1254 +                        break;
  1.1255 +                    }
  1.1256 +                case "SENTONBEHALFOFNAME":
  1.1257 +                    {
  1.1258 +                        // Always fired with "SENDUSINGACCOUNT" so is ignored
  1.1259 +                        break;
  1.1260 +                    }
  1.1261 +                case "SENDUSINGACCOUNT":
  1.1262 +                    {
  1.1263 +                        // Update pEp enabled status
  1.1264 +                        this.isStarted = false;
  1.1265 +                        this.SetIsEnabled((this.CurrentMailItem)?.GetEnableFormRegion() ?? false);
  1.1266 +
  1.1267 +                        // Refresh the UI
  1.1268 +                        this.ResolveAllRecipients();
  1.1269 +                        this.RequestRatingAndUIUpdate();
  1.1270 +                        RibbonCustomizations.Invalidate();
  1.1271 +
  1.1272 +                        break;
  1.1273 +                    }
  1.1274 +                case "TO":
  1.1275 +                    {
  1.1276 +                        if (this.isEnabled)
  1.1277 +                        {
  1.1278 +                            this.RequestRatingAndUIUpdate();
  1.1279 +                        }
  1.1280 +                        break;
  1.1281 +                    }
  1.1282 +            }
  1.1283 +        }
  1.1284 +
  1.1285 +        /// <summary>
  1.1286 +        /// Event handler for when a handshake dialog was updated.
  1.1287 +        /// </summary>
  1.1288 +        protected void HandshakeDialog_Updated(object sender, EventArgs e)
  1.1289 +        {
  1.1290 +            // Update current form region
  1.1291 +            this.RequestRatingAndUIUpdate();
  1.1292 +            
  1.1293 +            /* If a handshake is performed while having the same message open both in an inspector
  1.1294 +             * and an Window window, the one that didn't trigger the handshake won't get updated
  1.1295 +             * automatically. Therefore, after a handshake, we also update all other open windows.
  1.1296 +             */
  1.1297 +            try
  1.1298 +            {
  1.1299 +                Globals.ThisAddIn.RecalculateAllWindows(this);                
  1.1300 +            }
  1.1301 +            catch (Exception ex)
  1.1302 +            {
  1.1303 +                Log.Error("HandshakeDialog_Updated: Error updating other windows. " + ex.Message);
  1.1304 +            }
  1.1305 +        }
  1.1306 +
  1.1307 +        /// <summary>
  1.1308 +        /// Event handler for when a handshake dialog was closed.
  1.1309 +        /// </summary>
  1.1310 +        protected void HandshakeDialog_Closed(object sender, EventArgs e)
  1.1311 +        {
  1.1312 +            if (this.handshakeDialog != null)
  1.1313 +            {
  1.1314 +                this.handshakeDialog.OnUpdateStatus -= HandshakeDialog_Updated;
  1.1315 +                this.handshakeDialog.Closed -= HandshakeDialog_Closed;
  1.1316 +                this.handshakeDialog = null;
  1.1317 +            }
  1.1318 +        }
  1.1319 +
  1.1320 +        /// <summary>
  1.1321 +        /// Event handler called after the refresh timer has elapsed.
  1.1322 +        /// </summary>
  1.1323 +        private void TimerRefresh_Tick(object sender, EventArgs e)
  1.1324 +        {
  1.1325 +            bool tryAgain = false;
  1.1326 +#pragma warning disable 219
  1.1327 +            bool markForDownload = false;
  1.1328 +#pragma warning restore 219
  1.1329 +            this.TimerRefresh.Enabled = false; // Only once
  1.1330 +            Outlook.OlDownloadState dlState;
  1.1331 +
  1.1332 +            /* The Refresh/UI_Update process:
  1.1333 +             * There are the following components:
  1.1334 +             *   1. TimerRefresh_Tick
  1.1335 +             *        This is the main timer tick event handler called any time
  1.1336 +             *        a refresh was requested (RequestRatingAndUIUpdate) and hasn't been run yet. 
  1.1337 +             *        A refresh is requested either at initialization or when a property changes
  1.1338 +             *        (such as MailItem_PropertyChanged). It is on a timer as many 
  1.1339 +             *        property change events could occur rapidy, but only one refresh should
  1.1340 +             *        occur for performance reasons.
  1.1341 +             * 
  1.1342 +             *   2. ImmediateRatingAndUIUpdate
  1.1343 +             *        This will re-calculate the mail item's rating.
  1.1344 +             *        This internally just calls CryptableMailItem.StartProcessing.
  1.1345 +             * 
  1.1346 +             *   3. MailItem_ProcessingCompleted
  1.1347 +             *        When processing of the mail item is complete, this even handler will be called.
  1.1348 +             *        This will update the UI with the latest rating then call StartGetMirror.
  1.1349 +             *        The CopyStateToUI method is used which means any open privacy status form will also
  1.1350 +             *        be updated.
  1.1351 +             * 
  1.1352 +             *   4. MailItem_GetMirrorComplete
  1.1353 +             *        This is the final step in updating the UI, after a mirror is located, it's contents
  1.1354 +             *        will be shown in the unencrypted preview.
  1.1355 +             * 
  1.1356 +             * The general calling sequence is as shown above 1->4 with each component calling the next.
  1.1357 +             * However, for methods that update the mail item directly, commonly only 2->4 is needed.
  1.1358 +             */
  1.1359 +
  1.1360 +            // Ensure the tick method is not called more than once
  1.1361 +            if ((this.isEnabled) &&
  1.1362 +                (refreshOngoing == false))
  1.1363 +            {
  1.1364 +                this.refreshOngoing = true;
  1.1365 +
  1.1366 +                if ((this.cryptableMailItem != null) &&
  1.1367 +                    (this.cryptableMailItem.IsBeingProcessed == false))
  1.1368 +                {
  1.1369 +                    // Attempt to get the download state
  1.1370 +                    try
  1.1371 +                    {
  1.1372 +                        dlState = this.cryptableMailItem.DownloadState;
  1.1373 +                    }
  1.1374 +                    catch (Exception ex)
  1.1375 +                    {
  1.1376 +                        Log.Warning("TimerRefresh_Tick: Get DownloadState failed, " + ex.ToString());
  1.1377 +
  1.1378 +                        // Assume everything is downloaded, but try to download again as well
  1.1379 +                        dlState = Outlook.OlDownloadState.olFullItem;
  1.1380 +                        markForDownload = true;
  1.1381 +                    }
  1.1382 +
  1.1383 +                    if (dlState == Outlook.OlDownloadState.olFullItem)
  1.1384 +                    {
  1.1385 +                        this.ImmediateRatingAndUIUpdate();
  1.1386 +                    }
  1.1387 +                    else
  1.1388 +                    {
  1.1389 +                        markForDownload = true;
  1.1390 +                    }
  1.1391 +
  1.1392 +                    /* 12/16/2016: It could be verified via testing that setting the MarkForDownload property
  1.1393 +                     * can be a way to crash Outlook under certain circumstances (e.g. with IMAP on Outlook 2010 or on Windows 7). 
  1.1394 +                     * This then is not caught by a try/catch block and therefore has to be considered an Outlook bug.
  1.1395 +                     * It seems that in newer versions of Outlook/Windows, they fixed it, causing exceptions, if at all.
  1.1396 +                     * For now, the following is commented out to prevent a crash. If at any point we see that header-only
  1.1397 +                     * messages cause bigger issues, this decision has to be reevaluated.
  1.1398 +                     */
  1.1399 +                    //if (markForDownload)
  1.1400 +                    //{
  1.1401 +                    //    // Try to mark the message for full download
  1.1402 +                    //    try
  1.1403 +                    //    {
  1.1404 +                    //        this.cryptableMailItem.MarkForDownload = Outlook.OlRemoteStatus.olMarkedForDownload;
  1.1405 +                    //        tryAgain = true;
  1.1406 +                    //    }
  1.1407 +                    //    catch (Exception ex)
  1.1408 +                    //    {
  1.1409 +                    //        Log.Warning("TimerRefresh_Tick: MarkForDownload failed, " + ex.ToString());
  1.1410 +                    //    }
  1.1411 +                    //}
  1.1412 +                }
  1.1413 +                else
  1.1414 +                {
  1.1415 +                    repeatProcessing = true;
  1.1416 +                }
  1.1417 +
  1.1418 +                // Set the timer to refresh again later automatically
  1.1419 +                if (tryAgain)
  1.1420 +                {
  1.1421 +                    this.TimerRefresh.Interval = 100;
  1.1422 +                    this.TimerRefresh.Enabled = true;
  1.1423 +                }
  1.1424 +
  1.1425 +                this.refreshOngoing = false;
  1.1426 +            }
  1.1427 +        }
  1.1428 +
  1.1429 +        #endregion
  1.1430 +    }
  1.1431 +}