Wrappers/WatchedWindow.cs
author Thomas
Thu, 06 Sep 2018 12:21:31 +0200
branchOUT-497
changeset 2360 f01523e581fa
parent 2359 0e6191d039e4
child 2385 21b6ba5474f7
permissions -rw-r--r--
Some cleanup
Thomas@2359
     1
´╗┐using pEp.UI;
Thomas@2359
     2
using pEpCOMServerAdapterLib;
Thomas@2359
     3
using System;
Thomas@2359
     4
using System.ComponentModel;
Thomas@2359
     5
using System.Windows.Forms;
Thomas@2359
     6
using Outlook = Microsoft.Office.Interop.Outlook;
Thomas@2359
     7
Thomas@2359
     8
namespace pEp
Thomas@2359
     9
{
Thomas@2359
    10
    /// <summary>
Thomas@2359
    11
    /// Stores an Outlook Window with connected events.
Thomas@2359
    12
    /// </summary>
Thomas@2359
    13
    public abstract class WatchedWindow : IDisposable
Thomas@2359
    14
    {
Thomas@2359
    15
        private CryptableMailItem               cryptableMailItem           = null;
Thomas@2359
    16
        private bool                            displayMirrorRequested      = false;
Thomas@2359
    17
        private HandshakeDialog                 handshakeDialog             = null;
Thomas@2359
    18
        private bool                            isEnabled                   = true;
Thomas@2359
    19
        private bool                            isStarted                   = false;
Thomas@2359
    20
        private bool                            processingOngoing           = false;
Thomas@2359
    21
        private bool                            refreshOngoing              = false;
Thomas@2359
    22
        private bool                            repeatProcessing            = false;
Thomas@2359
    23
        private int                             repeatCounter               = 0;
Thomas@2359
    24
        private const int                       maxRepeatCount              = 5;
Thomas@2359
    25
Thomas@2359
    26
        private Outlook.MailItem                _CurrentMailItem            = null;
Thomas@2359
    27
Thomas@2360
    28
        #region Properties
Thomas@2359
    29
Thomas@2359
    30
        /// <summary>
Thomas@2359
    31
        /// The rating of the currently selected message.
Thomas@2359
    32
        /// </summary>
Thomas@2359
    33
        private pEpRating _Rating = pEpRating.pEpRatingUndefined;
Thomas@2359
    34
Thomas@2359
    35
        /// <summary>
Thomas@2359
    36
        /// The mail item that is connected to this Inspector/Explorer window.
Thomas@2359
    37
        /// </summary>
Thomas@2359
    38
        public Outlook.MailItem CurrentMailItem
Thomas@2359
    39
        {
Thomas@2359
    40
            get
Thomas@2359
    41
            {
Thomas@2359
    42
                return this._CurrentMailItem;
Thomas@2359
    43
            }
Thomas@2359
    44
            protected set
Thomas@2359
    45
            {
Thomas@2359
    46
                this._CurrentMailItem = value;
Thomas@2359
    47
            }
Thomas@2359
    48
        }
Thomas@2359
    49
Thomas@2359
    50
        /// <summary>
Thomas@2359
    51
        /// Gets or sets whether to disable the Force Protection option.
Thomas@2359
    52
        /// </summary>
Thomas@2359
    53
        public bool DisableForceProtection { get; set; } = false;
Thomas@2359
    54
Thomas@2359
    55
        /// <summary>
Thomas@2359
    56
        /// Gets or sets whether to send this message forcefully protected.
Thomas@2359
    57
        /// </summary>
Thomas@2359
    58
        public bool ForceProtection { get; set; } = false;
Thomas@2359
    59
Thomas@2359
    60
        /// <summary>
Thomas@2359
    61
        /// Gets or sets whether to send this message forcefully unencrypted.
Thomas@2359
    62
        /// </summary>
Thomas@2359
    63
        public bool ForceUnencrypted { get; set; } = false;
Thomas@2359
    64
Thomas@2359
    65
        /// <summary>
Thomas@2359
    66
        /// Gets or sets whether the message is a draft message.
Thomas@2359
    67
        /// </summary>
Thomas@2359
    68
        public bool IsDraft { get; set; } = false;
Thomas@2359
    69
Thomas@2359
    70
        /// <summary>
Thomas@2359
    71
        /// Gets or sets whether to always store this message as if on an untrusted server.
Thomas@2359
    72
        /// </summary>
Thomas@2359
    73
        public bool NeverUnsecure { get; set; } = false;
Thomas@2359
    74
Thomas@2359
    75
        /// <summary>
Thomas@2359
    76
        /// Gets the rating of this message.
Thomas@2359
    77
        /// </summary>
Thomas@2359
    78
        public pEpRating Rating
Thomas@2359
    79
        {
Thomas@2359
    80
            get { return this._Rating; }
Thomas@2359
    81
        }
Thomas@2359
    82
Thomas@2359
    83
        /// <summary>
Thomas@2359
    84
        /// Gets the associated Explorer/Inspector window. To be overwritten by child class.
Thomas@2359
    85
        /// </summary>
Thomas@2359
    86
        public abstract dynamic Window { get; }
Thomas@2359
    87
Thomas@2359
    88
        /// <summary>
Thomas@2359
    89
        /// Sets the rating of this message and updates the UI.
Thomas@2359
    90
        /// </summary>
Thomas@2359
    91
        /// <param name="rating">The message rating.</param>
Thomas@2359
    92
        public void SetRating(pEpRating rating)
Thomas@2359
    93
        {
Thomas@2359
    94
            this._Rating = rating;
Thomas@2359
    95
            RibbonCustomizations.Invalidate();
Thomas@2359
    96
        }
Thomas@2359
    97
Thomas@2359
    98
        /// <summary>
Thomas@2359
    99
        /// The timer that schedules the updates of this window.
Thomas@2359
   100
        /// </summary>
Thomas@2359
   101
        public System.Windows.Forms.Timer TimerRefresh { get; set; } = new System.Windows.Forms.Timer();
Thomas@2360
   102
Thomas@2359
   103
        #endregion
Thomas@2359
   104
Thomas@2359
   105
        #region Constructors / Destructors
Thomas@2359
   106
Thomas@2359
   107
        /// <summary>
Thomas@2359
   108
        /// Destructor.
Thomas@2359
   109
        /// </summary>
Thomas@2359
   110
        ~WatchedWindow()
Thomas@2359
   111
        {
Thomas@2359
   112
            this.Dispose(true);
Thomas@2359
   113
        }
Thomas@2359
   114
        #endregion
Thomas@2359
   115
Thomas@2359
   116
        #region Methods
Thomas@2359
   117
        /**************************************************************
Thomas@2359
   118
         * 
Thomas@2359
   119
         * Methods
Thomas@2359
   120
         * 
Thomas@2359
   121
         *************************************************************/
Thomas@2359
   122
Thomas@2359
   123
        /// <summary>
Thomas@2359
   124
        /// Releases all resources and disconnects internal events.
Thomas@2359
   125
        /// </summary>
Thomas@2359
   126
        public void Dispose()
Thomas@2359
   127
        {
Thomas@2359
   128
            this.Dispose(true);
Thomas@2359
   129
        }
Thomas@2359
   130
Thomas@2359
   131
        /// <summary>
Thomas@2359
   132
        /// Clean up any resources being used.
Thomas@2359
   133
        /// </summary>
Thomas@2359
   134
        /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
Thomas@2359
   135
        protected virtual void Dispose(bool disposing)
Thomas@2359
   136
        {
Thomas@2359
   137
            if (disposing)
Thomas@2359
   138
            {
Thomas@2360
   139
                // Disconnect cryptable mail item
Thomas@2360
   140
                if (this.cryptableMailItem != null)
Thomas@2360
   141
                {
Thomas@2360
   142
                    try
Thomas@2360
   143
                    {
Thomas@2360
   144
                        this.cryptableMailItem.PropertyChanged -= MailItem_PropertyChanged;
Thomas@2360
   145
                        this.cryptableMailItem.ProcessingCompleted -= MailItem_ProcessingCompleted;
Thomas@2360
   146
                        this.cryptableMailItem.GetMirrorCompleted -= MailItem_GetMirrorCompleted;
Thomas@2360
   147
                        this.cryptableMailItem.Open -= MailItem_Open;
Thomas@2360
   148
                        this.cryptableMailItem.Send -= MailItem_Send;
Thomas@2360
   149
                        this.cryptableMailItem.OriginallyEncryptedStatusUpdated -= CryptableMailItem_OriginallyEncryptedStatusUpdated;
Thomas@2360
   150
                    }
Thomas@2360
   151
                    catch { }
Thomas@2360
   152
Thomas@2360
   153
                    this.cryptableMailItem.Dispose();
Thomas@2360
   154
                    this.cryptableMailItem = null;
Thomas@2360
   155
                }
Thomas@2360
   156
Thomas@2360
   157
                // Disconnect other
Thomas@2360
   158
                this.SetIsEnabled(false);
Thomas@2360
   159
Thomas@2359
   160
                // Set Outlook objects to null
Thomas@2359
   161
                this._CurrentMailItem = null;
Thomas@2360
   162
Thomas@2360
   163
                // Dispose of timer
Thomas@2360
   164
                this.TimerRefresh.Dispose();
Thomas@2359
   165
            }
Thomas@2359
   166
        }
Thomas@2360
   167
Thomas@2359
   168
        /// <summary>
Thomas@2359
   169
        /// Builds the latest state of the encryption status manager then shows the UI.
Thomas@2359
   170
        /// </summary>
Thomas@2359
   171
        public void BuildAndShowManager()
Thomas@2359
   172
        {
Thomas@2359
   173
            /* Resolve all recipients -- this ensures the identities list is correctly populated
Thomas@2359
   174
             * 
Thomas@2359
   175
             * Note: The PropertyChanged changed event must be disconnected before trying to resolve.
Thomas@2359
   176
             * This is because the resolve process can modify the contents of the mail item which triggers an event.
Thomas@2359
   177
             * The PropertyChanged event would then trigger a UI refresh cycle. However, because the GetManagerState itself 
Thomas@2359
   178
             * is called within the UI refresh, an infinite loop could occur trying to resolve a recipient that
Thomas@2359
   179
             * cannot be resolved (no address).
Thomas@2359
   180
             */
Thomas@2359
   181
            try
Thomas@2359
   182
            {
Thomas@2359
   183
                this.ResolveAllRecipients();
Thomas@2359
   184
            }
Thomas@2359
   185
            catch (Exception ex)
Thomas@2359
   186
            {
Thomas@2359
   187
                Log.Verbose("BuildAndShowManager: Error resolving recipients. " + ex.ToString());
Thomas@2359
   188
            }
Thomas@2359
   189
Thomas@2359
   190
            // Build the dialog
Thomas@2359
   191
            try
Thomas@2359
   192
            {
Thomas@2359
   193
                // The PEPMessage to build the dialog with
Thomas@2359
   194
                PEPMessage message = null;
Thomas@2359
   195
Thomas@2359
   196
                // The own identity to build the dialog with
Thomas@2359
   197
                PEPIdentity myself = this.cryptableMailItem?.Myself;
Thomas@2359
   198
Thomas@2359
   199
                // If message is a draft, create it directly from the Outlook mail item
Thomas@2359
   200
                if (this.IsDraft)
Thomas@2359
   201
                {
Thomas@2359
   202
                    Log.Verbose("BuildAndShowManager: Creating PEPMessage from draft.");
Thomas@2359
   203
Thomas@2359
   204
                    if (PEPMessage.Create(this._CurrentMailItem, out message) != Globals.ReturnStatus.Success)
Thomas@2359
   205
                    {
Thomas@2359
   206
                        Log.Error("BuildAndShowManager: Error creating PEPMessage from draft.");
Thomas@2359
   207
                        message = null;
Thomas@2359
   208
                    }
Thomas@2359
   209
                    else
Thomas@2359
   210
                    {
Thomas@2359
   211
                        // Calculate rating
Thomas@2359
   212
                        message.Rating = message.GetOutgoingRating();
Thomas@2359
   213
Thomas@2359
   214
                        // If Force Protection is set, assign a random GUID
Thomas@2359
   215
                        if ((this.ForceProtection) &&
Thomas@2359
   216
                            (this.DisableForceProtection == false))
Thomas@2359
   217
                        {
Thomas@2359
   218
                            message.ForceProtectionId = Guid.NewGuid().ToString();
Thomas@2359
   219
                        }
Thomas@2359
   220
Thomas@2359
   221
                        // If message is Force Unencrypted, assign it
Thomas@2359
   222
                        message.ForceUnencrypted = this.ForceUnencrypted;
Thomas@2359
   223
                    }
Thomas@2359
   224
                }
Thomas@2359
   225
                else
Thomas@2359
   226
                {
Thomas@2359
   227
                    // Else, use either the cryptable mail item's associated mirror or message
Thomas@2359
   228
                    message = this.cryptableMailItem?.Mirror ?? this.cryptableMailItem?.Message;
Thomas@2359
   229
                    Log.Verbose(string.Format("BuildAndShowManager: Message {0} retrieved from CryptableMailItem", ((message != null) ? "successfully" : "could not be")));
Thomas@2359
   230
Thomas@2359
   231
                    // As fallback, if we don't have a message yet, create it
Thomas@2359
   232
                    if (message == null)
Thomas@2359
   233
                    {
Thomas@2359
   234
                        Log.Verbose("BuildAndShowManager: Using fallback method to get message.");
Thomas@2359
   235
Thomas@2359
   236
                        Outlook.MailItem mirror = null;
Thomas@2359
   237
Thomas@2359
   238
                        try
Thomas@2359
   239
                        {
Thomas@2359
   240
                            // For securely stored mails, try to look up mirror
Thomas@2359
   241
                            if (this._CurrentMailItem?.GetIsSecurelyStored() == true)
Thomas@2359
   242
                            {
Thomas@2359
   243
                                mirror = this._CurrentMailItem?.GetMirror();
Thomas@2359
   244
Thomas@2359
   245
                                if (mirror != null)
Thomas@2359
   246
                                {
Thomas@2359
   247
                                    // If mirror is found, use it to create PEPMessage
Thomas@2359
   248
                                    Log.Verbose("BuildAndShowManager: Mirror found.");
Thomas@2359
   249
Thomas@2359
   250
                                    if (PEPMessage.Create(mirror, out message) != Globals.ReturnStatus.Success)
Thomas@2359
   251
                                    {
Thomas@2359
   252
                                        message = null;
Thomas@2359
   253
                                        Log.Error("BuildAndShowManager: Error creating PEPMessage.");
Thomas@2359
   254
                                    }
Thomas@2359
   255
                                    else
Thomas@2359
   256
                                    {
Thomas@2359
   257
                                        message.Rating = AdapterExtensions.ReevaluateMessageRating(message);
Thomas@2359
   258
                                    }
Thomas@2359
   259
                                }
Thomas@2359
   260
                                else
Thomas@2359
   261
                                {
Thomas@2359
   262
                                    // If no mirror is found, decrypt message and use decrypted one (do not 
Thomas@2359
   263
                                    // decrypt forcefully protected messages).
Thomas@2359
   264
                                    if ((PEPMessage.Create(this._CurrentMailItem, out message) == Globals.ReturnStatus.Success) &&
Thomas@2359
   265
                                        (string.IsNullOrEmpty(message.ForceProtectionId)))
Thomas@2359
   266
                                    {
Thomas@2359
   267
                                        var msgProcessor = new MsgProcessor();
Thomas@2359
   268
                                        PEPMessage decryptedMsg = null;
Thomas@2359
   269
                                        string[] keyList;
Thomas@2359
   270
                                        pEpDecryptFlags flags = pEpDecryptFlags.pEpDecryptFlagsNone;
Thomas@2359
   271
                                        pEpRating rating = msgProcessor.Decrypt(ref message, out decryptedMsg, out keyList, ref flags);
Thomas@2359
   272
                                        if (decryptedMsg != null)
Thomas@2359
   273
                                        {
Thomas@2359
   274
                                            message = decryptedMsg;
Thomas@2359
   275
                                        }
Thomas@2359
   276
                                        message.Rating = rating;
Thomas@2359
   277
                                    }
Thomas@2359
   278
                                    else
Thomas@2359
   279
                                    {
Thomas@2359
   280
                                        message = null;
Thomas@2359
   281
                                        Log.Error("BuildAndShowManager: Error creating PEPMessage from mirror.");
Thomas@2359
   282
                                    }
Thomas@2359
   283
                                }
Thomas@2359
   284
                            }
Thomas@2359
   285
Thomas@2359
   286
                            // If we don't have a PEPMessage yet, create it
Thomas@2359
   287
                            if (message == null)
Thomas@2359
   288
                            {
Thomas@2359
   289
                                Log.Verbose("BuildAndShowManager: Creating PEPMessage.");
Thomas@2359
   290
Thomas@2359
   291
                                if (PEPMessage.Create(this._CurrentMailItem, out message) != Globals.ReturnStatus.Success)
Thomas@2359
   292
                                {
Thomas@2359
   293
                                    message = null;
Thomas@2359
   294
                                    Log.Error("BuildAndShowManager: Error creating PEPMessage.");
Thomas@2359
   295
                                }
Thomas@2359
   296
                                else
Thomas@2359
   297
                                {
Thomas@2359
   298
                                    message.Rating = AdapterExtensions.ReevaluateMessageRating(message);
Thomas@2359
   299
                                }
Thomas@2359
   300
                            }
Thomas@2359
   301
Thomas@2359
   302
                            // Get myself identiy if we don't have it yet
Thomas@2359
   303
                            if (myself == null)
Thomas@2359
   304
                            {
Thomas@2359
   305
                                myself = this._CurrentMailItem.GetMyselfIdentity();
Thomas@2359
   306
                            }
Thomas@2359
   307
                        }
Thomas@2359
   308
                        catch (Exception ex)
Thomas@2359
   309
                        {
Thomas@2359
   310
                            Log.Error("FormRegionPrivacyStatus.Message: Error converting message. " + ex.ToString());
Thomas@2359
   311
                        }
Thomas@2359
   312
                        finally
Thomas@2359
   313
                        {
Thomas@2359
   314
                            mirror = null;
Thomas@2359
   315
                        }
Thomas@2359
   316
                    }
Thomas@2359
   317
                }
Thomas@2359
   318
Thomas@2359
   319
                // Build dialog
Thomas@2359
   320
                if (message != null)
Thomas@2359
   321
                {
Thomas@2359
   322
                    handshakeDialog = new HandshakeDialog(message, myself, this.IsDraft);
Thomas@2359
   323
                    handshakeDialog.OnUpdateStatus += HandshakeDialog_Updated;
Thomas@2359
   324
                    handshakeDialog.Closed += HandshakeDialog_Closed;
Thomas@2359
   325
                    handshakeDialog.Show();
Thomas@2359
   326
                }
Thomas@2359
   327
                else
Thomas@2359
   328
                {
Thomas@2359
   329
                    throw new Exception("Could not build handshake dialog. Message is null.");
Thomas@2359
   330
                }
Thomas@2359
   331
            }
Thomas@2359
   332
            catch (Exception ex)
Thomas@2359
   333
            {
Thomas@2359
   334
                Globals.StopAndSendCrashReport(ex);
Thomas@2359
   335
            }
Thomas@2359
   336
        }
Thomas@2359
   337
Thomas@2359
   338
        /// <summary>
Thomas@2359
   339
        /// Schedules for the pEp rating and UI (including displayed mirror) to be updated.
Thomas@2359
   340
        /// This can be called many times with no issue as the update is only run every n milliseconds.
Thomas@2359
   341
        /// </summary>
Thomas@2359
   342
        public void RequestRatingAndUIUpdate()
Thomas@2359
   343
        {
Thomas@2359
   344
            if (this.isEnabled)
Thomas@2359
   345
            {
Thomas@2359
   346
                this.TimerRefresh.Enabled = true;
Thomas@2359
   347
            }
Thomas@2359
   348
        }
Thomas@2359
   349
Thomas@2359
   350
        /// <summary>
Thomas@2359
   351
        /// Immediately starts the update of UI rating based on the associated mail item.
Thomas@2359
   352
        /// This will start decryption as necessary and also will update the displayed mirror.
Thomas@2359
   353
        /// This method by-passes the refresh timer completely.
Thomas@2359
   354
        /// WARNING: This method assumes the message is fully downloaded already.
Thomas@2359
   355
        /// </summary>
Thomas@2359
   356
        private void ImmediateRatingAndUIUpdate()
Thomas@2359
   357
        {
Thomas@2359
   358
            if ((this.isEnabled) &&
Thomas@2359
   359
                (this.cryptableMailItem != null))
Thomas@2359
   360
            {
Thomas@2359
   361
                Log.Verbose("ImmediateRatingAndUIUpdate: Starting processing.");
Thomas@2359
   362
Thomas@2359
   363
                // Start the rating calculation/decryption process
Thomas@2359
   364
                this.cryptableMailItem.StartProcessing();
Thomas@2359
   365
                this.processingOngoing = true;
Thomas@2359
   366
            }
Thomas@2359
   367
        }
Thomas@2359
   368
Thomas@2359
   369
        /// <summary>
Thomas@2359
   370
        /// Resets the Enabled status of this form region and recalculates the rating if necessary.
Thomas@2359
   371
        /// </summary>
Thomas@2359
   372
        /// <param name="enable">Whether to enable the form region.</param>
Thomas@2359
   373
        public void UpdateFormRegion(bool enable)
Thomas@2359
   374
        {
Thomas@2359
   375
            this.SetIsEnabled(enable);
Thomas@2359
   376
Thomas@2359
   377
            // Refresh the UI
Thomas@2359
   378
            if (enable)
Thomas@2359
   379
            {
Thomas@2359
   380
                this.ResolveAllRecipients();
Thomas@2359
   381
                this.RequestRatingAndUIUpdate();
Thomas@2359
   382
            }
Thomas@2359
   383
        }
Thomas@2359
   384
Thomas@2359
   385
        /// <summary>
Thomas@2359
   386
        /// Workaround method to update the current inspector window. This is done by moving the mail item
Thomas@2359
   387
        /// to a temporary folder first and then back to the current folder. Both folders CANNOT be the same.
Thomas@2359
   388
        /// As a fallback, the mail item stays in the temporary folder if moving back to the current folder
Thomas@2359
   389
        /// fails.
Thomas@2359
   390
        /// </summary>
Thomas@2359
   391
        private void UpdateInspector()
Thomas@2359
   392
        {
Thomas@2359
   393
            Outlook.Application application = null;
Thomas@2359
   394
            Outlook.Folder currentFolder = null;
Thomas@2359
   395
            Outlook.Folder tempFolder = null;
Thomas@2359
   396
            Outlook.Inspector currentInspector = null;
Thomas@2359
   397
            Outlook.Inspector newInspector = null;
Thomas@2359
   398
            Outlook.MailItem tempMailItem = null;
Thomas@2359
   399
            Outlook.Store store = null;
Thomas@2359
   400
            Outlook.MailItem omi = this.CurrentMailItem;
Thomas@2359
   401
Thomas@2359
   402
            if (omi != null)
Thomas@2359
   403
            {
Thomas@2359
   404
                try
Thomas@2359
   405
                {
Thomas@2359
   406
                    application = omi.Application;
Thomas@2359
   407
                    currentInspector = omi.GetInspector;
Thomas@2359
   408
                    currentFolder = omi.Parent as Outlook.Folder;
Thomas@2359
   409
Thomas@2359
   410
                    if ((currentInspector != null) &&
Thomas@2359
   411
                        (application != null) &&
Thomas@2359
   412
                        (currentFolder != null))
Thomas@2359
   413
                    {
Thomas@2359
   414
                        var left = currentInspector.Left;
Thomas@2359
   415
                        var top = currentInspector.Top;
Thomas@2359
   416
                        var width = currentInspector.Width;
Thomas@2359
   417
                        var height = currentInspector.Height;
Thomas@2359
   418
                        var windowState = currentInspector.WindowState;
Thomas@2359
   419
Thomas@2359
   420
                        /* Check, if in trusted store. In that case, use the default drafts folder
Thomas@2359
   421
                         * as temporary folder. If the store is untrusted, use the pEp drafts folder.
Thomas@2359
   422
                         */
Thomas@2359
   423
                        store = currentFolder.Store;
Thomas@2359
   424
                        if (store?.GetIsSecureStorageEnabled() ?? false)
Thomas@2359
   425
                        {
Thomas@2359
   426
                            tempFolder = Globals.ThisAddIn.GetPEPStoreDraftsFolder();
Thomas@2359
   427
                        }
Thomas@2359
   428
                        else
Thomas@2359
   429
                        {
Thomas@2359
   430
                            tempFolder = store.GetDefaultFolder(Outlook.OlDefaultFolders.olFolderDrafts) as Outlook.Folder;
Thomas@2359
   431
                        }
Thomas@2359
   432
Thomas@2359
   433
                        if (tempFolder != null)
Thomas@2359
   434
                        {
Thomas@2359
   435
                            tempMailItem = omi.Move(tempFolder) as Outlook.MailItem;
Thomas@2359
   436
Thomas@2359
   437
                            if (tempMailItem != null)
Thomas@2359
   438
                            {
Thomas@2359
   439
                                try
Thomas@2359
   440
                                {
Thomas@2359
   441
                                    omi = tempMailItem.Move(currentFolder) as Outlook.MailItem;
Thomas@2359
   442
                                }
Thomas@2359
   443
                                catch
Thomas@2359
   444
                                {
Thomas@2359
   445
                                    omi = tempMailItem.Copy();
Thomas@2359
   446
                                }
Thomas@2359
   447
Thomas@2359
   448
                                newInspector = application.Inspectors.Add(omi);
Thomas@2359
   449
Thomas@2359
   450
                                if (windowState == Outlook.OlWindowState.olNormalWindow)
Thomas@2359
   451
                                {
Thomas@2359
   452
                                    newInspector.Left = left;
Thomas@2359
   453
                                    newInspector.Top = top;
Thomas@2359
   454
                                    newInspector.Width = width;
Thomas@2359
   455
                                    newInspector.Height = height;
Thomas@2359
   456
                                }
Thomas@2359
   457
Thomas@2359
   458
                                newInspector.Display();
Thomas@2359
   459
                                newInspector.WindowState = windowState;
Thomas@2359
   460
Thomas@2359
   461
                                repeatProcessing = false;
Thomas@2359
   462
                            }
Thomas@2359
   463
                        }
Thomas@2359
   464
                        else
Thomas@2359
   465
                        {
Thomas@2359
   466
                            Log.Error("UpdateInspector: Cannot get temporary folder.");
Thomas@2359
   467
                        }
Thomas@2359
   468
                    }
Thomas@2359
   469
                    else
Thomas@2359
   470
                    {
Thomas@2359
   471
                        Log.Verbose("UpdateInspector: Error retrieving inspector window or application.");
Thomas@2359
   472
                    }
Thomas@2359
   473
                }
Thomas@2359
   474
                catch (Exception ex)
Thomas@2359
   475
                {
Thomas@2359
   476
                    Log.Verbose("UpdateInspector: Error updating inspector window. " + ex.ToString());
Thomas@2359
   477
                }
Thomas@2359
   478
                finally
Thomas@2359
   479
                {
Thomas@2359
   480
                    application = null;
Thomas@2359
   481
                    currentInspector = null;
Thomas@2359
   482
                    newInspector = null;
Thomas@2359
   483
                    omi = null;
Thomas@2359
   484
                    tempMailItem = null;
Thomas@2359
   485
                }
Thomas@2359
   486
            }
Thomas@2359
   487
        }
Thomas@2359
   488
Thomas@2359
   489
        /// <summary>
Thomas@2359
   490
        /// Clears the associated unencrypted preview and displays the given note (if any).
Thomas@2359
   491
        /// </summary>
Thomas@2359
   492
        /// <param name="note">The note to display.</param>
Thomas@2359
   493
        private void SetNote(string note = null)
Thomas@2359
   494
        {
Thomas@2359
   495
            WindowFormRegionCollection formRegions = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveWindow()];
Thomas@2359
   496
Thomas@2359
   497
            if ((formRegions != null) &&
Thomas@2359
   498
                (string.IsNullOrEmpty(note) == false))
Thomas@2359
   499
            {
Thomas@2359
   500
                if ((formRegions.FormRegionPreviewUnencrypted != null) &&
Thomas@2359
   501
                    (formRegions.FormRegionPreviewUnencrypted.Visible))
Thomas@2359
   502
                {
Thomas@2359
   503
                    formRegions.FormRegionPreviewUnencrypted.DisplayState.SetNote(note);
Thomas@2359
   504
                }
Thomas@2359
   505
            }
Thomas@2359
   506
        }
Thomas@2359
   507
Thomas@2359
   508
        /// <summary>
Thomas@2359
   509
        /// Sets whether processing of the mail item is enabled.
Thomas@2359
   510
        /// This should commonly be set from the .GetIsPEPEnabled() value.
Thomas@2359
   511
        /// </summary>
Thomas@2359
   512
        private void SetIsEnabled(bool enabled)
Thomas@2359
   513
        {
Thomas@2359
   514
            PEPIdentity currIdent;
Thomas@2359
   515
            Globals.ReturnStatus sts;
Thomas@2359
   516
            Outlook.Recipient currUser = null;
Thomas@2359
   517
            Outlook.Account currAccount = null;
Thomas@2359
   518
            Outlook.Account sendingAccount = null;
Thomas@2359
   519
            Outlook.NameSpace ns = null;
Thomas@2359
   520
Thomas@2359
   521
            this.isEnabled = enabled;
Thomas@2359
   522
Thomas@2359
   523
            if (enabled)
Thomas@2359
   524
            {
Thomas@2359
   525
                // Do not allow initialization more than once
Thomas@2359
   526
                if (this.isStarted == false)
Thomas@2359
   527
                {
Thomas@2359
   528
                    /* It's possible for new draft MailItems to be created outside the context of an account.
Thomas@2359
   529
                     * In this situation the SendUsingAccount will always be null which of course breaks several pEp operations.
Thomas@2359
   530
                     * The operations themselves cannot make the assumption about what account information to use.
Thomas@2359
   531
                     * Therefore, the situation is detected here and for draft mail items a null SendUsingAccount will be 
Thomas@2359
   532
                     * set with the session's default account.
Thomas@2359
   533
                     */
Thomas@2360
   534
                    if (this.IsDraft)
Thomas@2359
   535
                    {
Thomas@2360
   536
                        try
Thomas@2359
   537
                        {
Thomas@2359
   538
                            sendingAccount = this._CurrentMailItem.SendUsingAccount;
Thomas@2359
   539
                            if (sendingAccount == null)
Thomas@2359
   540
                            {
Thomas@2360
   541
                                ns = Globals.ThisAddIn.Application.Session;
Thomas@2360
   542
                                currUser = ns.CurrentUser;
Thomas@2359
   543
                                sts = PEPIdentity.Create(currUser, out currIdent);
Thomas@2359
   544
Thomas@2359
   545
                                if (sts == Globals.ReturnStatus.Success)
Thomas@2359
   546
                                {
Thomas@2359
   547
                                    sendingAccount = AccountExtensions.GetDefaultAccount(Outlook.OlDefaultFolders.olFolderDrafts);
Thomas@2359
   548
                                    if (sendingAccount != null)
Thomas@2359
   549
                                    {
Thomas@2359
   550
                                        this._CurrentMailItem.SendUsingAccount = currAccount;
Thomas@2359
   551
                                    }
Thomas@2359
   552
                                }
Thomas@2359
   553
                            }
Thomas@2359
   554
Thomas@2359
   555
                            // Check if account is already registered in pEp list and add it if necessary
Thomas@2359
   556
                            var acctSettings = Globals.ThisAddIn.Settings.GetAccountSettings(sendingAccount?.SmtpAddress);
Thomas@2359
   557
                            if (acctSettings == null)
Thomas@2359
   558
                            {
Thomas@2359
   559
                                Log.Verbose("SetIsEnabled: New account detected. Creating pEp settings.");
Thomas@2359
   560
Thomas@2359
   561
                                // Create pEp settings for the new account
Thomas@2359
   562
                                acctSettings = sendingAccount.CreatePEPSettings();
Thomas@2359
   563
Thomas@2359
   564
                                // Add account to list
Thomas@2359
   565
                                Globals.ThisAddIn.Settings.AccountsAddedWhileRunningList.Add(acctSettings?.SmtpAddress);
Thomas@2359
   566
                                Log.Verbose("SetIsEnabled: New account registered in pEp settings.");
Thomas@2359
   567
Thomas@2359
   568
                                // Generate key
Thomas@2359
   569
                                Globals.ThisAddIn.RegisterMyself(acctSettings);
Thomas@2359
   570
                                Log.Verbose("SetIsEnabled: Myself registered.");
Thomas@2359
   571
Thomas@2359
   572
                                // Set rules and view filters
Thomas@2359
   573
                                Globals.ThisAddIn.SetRulesAndViewFilters(sendingAccount);
Thomas@2359
   574
                            }
Thomas@2359
   575
                        }
Thomas@2360
   576
                        catch (Exception ex)
Thomas@2360
   577
                        {
Thomas@2360
   578
                            Log.Error("SetIsEnabled: Error occured. " + ex.ToString());
Thomas@2360
   579
                        }
Thomas@2360
   580
                        finally
Thomas@2360
   581
                        {
Thomas@2360
   582
                            currAccount = null;
Thomas@2360
   583
                            currUser = null;
Thomas@2360
   584
                            ns = null;
Thomas@2360
   585
                            sendingAccount = null;
Thomas@2360
   586
                        }
Thomas@2359
   587
                    }
Thomas@2359
   588
Thomas@2359
   589
                    // Connect refresh timer
Thomas@2359
   590
                    this.TimerRefresh.Tick += TimerRefresh_Tick;
Thomas@2359
   591
                    this.isStarted = true;
Thomas@2359
   592
                }
Thomas@2359
   593
            }
Thomas@2359
   594
            else
Thomas@2359
   595
            {
Thomas@2359
   596
                // Stop and disconnect the refresh timer
Thomas@2359
   597
                this.TimerRefresh.Stop();
Thomas@2359
   598
                this.TimerRefresh.Enabled = false;
Thomas@2359
   599
                this.TimerRefresh.Tick -= TimerRefresh_Tick;
Thomas@2359
   600
Thomas@2359
   601
                this.isStarted = false;
Thomas@2359
   602
            }
Thomas@2359
   603
        }
Thomas@2359
   604
Thomas@2359
   605
        /// <summary>
Thomas@2359
   606
        /// Resolves all recipients of the Outlook mail item.
Thomas@2359
   607
        /// </summary>
Thomas@2359
   608
        private void ResolveAllRecipients()
Thomas@2359
   609
        {
Thomas@2359
   610
            if ((this.isEnabled) &&
Thomas@2359
   611
                (this.cryptableMailItem != null))
Thomas@2359
   612
            {
Thomas@2359
   613
                /*
Thomas@2359
   614
                 * Note: The PropertyChanged changed event must be disconnected before trying to resolve.
Thomas@2359
   615
                 * This is because the resolve process can modify the contents of the mail item which triggers an event.
Thomas@2359
   616
                 * The PropertyChanged event would then trigger a UI refresh cycle. However, because the GetManagerState itself 
Thomas@2359
   617
                 * is called within the UI refresh, an infinite loop could occur trying to resolve a recipient that
Thomas@2359
   618
                 * cannot be resolved(no address).
Thomas@2359
   619
                 */
Thomas@2359
   620
                try
Thomas@2359
   621
                {
Thomas@2359
   622
                    this.cryptableMailItem.PropertyChanged -= MailItem_PropertyChanged;
Thomas@2359
   623
                    this.cryptableMailItem.ResolveAllRecipients();
Thomas@2359
   624
                    this.cryptableMailItem.PropertyChanged += MailItem_PropertyChanged;
Thomas@2359
   625
                }
Thomas@2359
   626
                catch (Exception ex)
Thomas@2359
   627
                {
Thomas@2359
   628
                    Log.Error("Error resolving recipients. " + ex.ToString());
Thomas@2359
   629
                }
Thomas@2359
   630
            }
Thomas@2359
   631
        }
Thomas@2359
   632
        #endregion
Thomas@2359
   633
Thomas@2359
   634
        #region Event Handling
Thomas@2359
   635
        /**************************************************************
Thomas@2359
   636
         * 
Thomas@2359
   637
         * Event Handling
Thomas@2359
   638
         * 
Thomas@2359
   639
         *************************************************************/
Thomas@2359
   640
Thomas@2359
   641
        protected void InitializeMailItem(bool isInlineResponse = false)
Thomas@2359
   642
        {
Thomas@2359
   643
            bool enableFormRegion = false;
Thomas@2359
   644
            bool cancelOpenEvent = false;
Thomas@2359
   645
            bool isSecureAttachedMail = false;
Thomas@2359
   646
            string messageId = null;
Thomas@2359
   647
Thomas@2359
   648
            try
Thomas@2360
   649
            {
Thomas@2359
   650
                // Check if draft
Thomas@2359
   651
                this.IsDraft = this._CurrentMailItem.GetIsDraft();
Thomas@2359
   652
Thomas@2359
   653
                /* Set immediately a provisional rating in order to have a less flickery
Thomas@2359
   654
                 * UI experience.
Thomas@2359
   655
                 * The provisional rating is either a stored rating or, in case we have a
Thomas@2359
   656
                 * reply message, the rating of the original (the item we reply to).
Thomas@2359
   657
                 * This provisional rating will be replace with the real one once the full
Thomas@2359
   658
                 * processing is complete.
Thomas@2359
   659
                 */
Thomas@2359
   660
                pEpRating provisionalRating = pEpRating.pEpRatingUndefined;
Thomas@2359
   661
Thomas@2359
   662
                // Try to get an original rating (in case of reply messages)
Thomas@2359
   663
                if ((this.IsDraft) &&
Thomas@2359
   664
                    (this._CurrentMailItem?.Recipients?.Count > 0))
Thomas@2359
   665
                {
Thomas@2359
   666
                    string originalRatingString = this._CurrentMailItem.GetUserProperty(CryptableMailItem.USER_PROPERTY_KEY_ORIGINAL_RATING) as string;
Thomas@2359
   667
Thomas@2359
   668
                    // If we have an original rating, parse it and set it.
Thomas@2359
   669
                    if (string.IsNullOrEmpty(originalRatingString) == false)
Thomas@2359
   670
                    {
Thomas@2359
   671
                        provisionalRating = AdapterExtensions.ParseRatingString(originalRatingString);
Thomas@2359
   672
                    }
Thomas@2359
   673
                }
Thomas@2359
   674
                else
Thomas@2359
   675
                {
Thomas@2359
   676
                    // Try to get rating from db
Thomas@2359
   677
                    provisionalRating = PEPDatabase.GetRating(this._CurrentMailItem.EntryID);
Thomas@2359
   678
Thomas@2359
   679
                    // If there is no rating in the db, use stored or default rating
Thomas@2359
   680
                    if (provisionalRating == pEpRating.pEpRatingUndefined)
Thomas@2359
   681
                    {
Thomas@2359
   682
                        provisionalRating = this._CurrentMailItem.GetStoredRating() ?? pEpRating.pEpRatingUndefined;
Thomas@2359
   683
                    }
Thomas@2359
   684
                }
Thomas@2359
   685
Thomas@2359
   686
                // Only set rating if one has been retrieved
Thomas@2359
   687
                if (provisionalRating != pEpRating.pEpRatingUndefined)
Thomas@2359
   688
                {
Thomas@2359
   689
                    this.SetRating(provisionalRating);
Thomas@2359
   690
                    Log.Verbose("FormRegionPrivacyStatus_FormRegionShowing: Provisional rating {0} shown.", Enum.GetName(typeof(pEpRating), provisionalRating));
Thomas@2359
   691
                }
Thomas@2359
   692
Thomas@2359
   693
Thomas@2359
   694
                // Do not process S/MIME messages
Thomas@2359
   695
                if (this._CurrentMailItem.GetIsSMIMEEnabled())
Thomas@2359
   696
                {
Thomas@2359
   697
                    Log.Verbose("FormRegionPrivacyStatus_FormRegionShowing: S/MIME message detected. Won't be processed.");
Thomas@2359
   698
Thomas@2359
   699
                    // Set unencrypted rating
Thomas@2359
   700
                    this.SetRating(pEpRating.pEpRatingUnencrypted);
Thomas@2359
   701
Thomas@2359
   702
                    // Set icon(s) if necessary     
Thomas@2359
   703
                    if ((IsDraft == false) &&
Thomas@2359
   704
                        (this._CurrentMailItem.SetEncryptionIcons()))
Thomas@2359
   705
                    {
Thomas@2359
   706
                        try
Thomas@2359
   707
                        {
Thomas@2359
   708
                            this._CurrentMailItem.Save();
Thomas@2359
   709
                        }
Thomas@2359
   710
                        catch (Exception ex)
Thomas@2359
   711
                        {
Thomas@2359
   712
                            Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Error saving message after changing icon. " + ex.ToString());
Thomas@2359
   713
                        }
Thomas@2359
   714
                    }
Thomas@2359
   715
Thomas@2359
   716
                    return;
Thomas@2359
   717
                }
Thomas@2359
   718
Thomas@2359
   719
                /* Check if item is attached mail. For performance reasons,
Thomas@2359
   720
                 * only do the whole check if an item has been loaded to the
Thomas@2359
   721
                 * cache of attached mails and if item might be secure.
Thomas@2359
   722
                 */
Thomas@2359
   723
                if ((PEPAttachment.AttachedMailsCache.Count > 0) &&
Thomas@2359
   724
                    (this._CurrentMailItem.Attachments?.Count == 2))
Thomas@2359
   725
                {
Thomas@2359
   726
                    try
Thomas@2359
   727
                    {
Thomas@2359
   728
                        // Check if mail item is an attached mail
Thomas@2359
   729
                        if (this._CurrentMailItem.GetIsAttachedMail(out messageId))
Thomas@2359
   730
                        {
Thomas@2359
   731
                            Outlook.MailItem mirror = null;
Thomas@2359
   732
                            PEPMessage pEpMessage;
Thomas@2359
   733
Thomas@2359
   734
                            // Try to get the mirror
Thomas@2359
   735
                            mirror = this._CurrentMailItem.GetMirror(messageId);
Thomas@2359
   736
Thomas@2359
   737
                            // If mirror was not found, decrypt and create mirror
Thomas@2359
   738
                            if (mirror != null)
Thomas@2359
   739
                            {
Thomas@2359
   740
                                isSecureAttachedMail = true;
Thomas@2359
   741
                            }
Thomas@2359
   742
                            else
Thomas@2359
   743
                            {
Thomas@2359
   744
                                if ((PEPMessage.Create(this._CurrentMailItem, out pEpMessage) == Globals.ReturnStatus.Success) &&
Thomas@2359
   745
                                    (pEpMessage.IsSecure))
Thomas@2359
   746
                                {
Thomas@2359
   747
                                    PEPMessage decryptedMessage;
Thomas@2359
   748
                                    MsgProcessor msgProcessor = new MsgProcessor();
Thomas@2359
   749
                                    if (msgProcessor.Decrypt(pEpMessage, out decryptedMessage))
Thomas@2359
   750
                                    {
Thomas@2359
   751
                                        isSecureAttachedMail = true;
Thomas@2359
   752
                                        mirror = this._CurrentMailItem.CreateMirrorOMI(messageId);
Thomas@2359
   753
                                        decryptedMessage.ApplyTo(mirror, true, false);
Thomas@2359
   754
                                        mirror?.Save();
Thomas@2359
   755
                                    }
Thomas@2359
   756
                                    else
Thomas@2359
   757
                                    {
Thomas@2359
   758
                                        Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Decryption of attached mail was not successful.");
Thomas@2359
   759
                                    }
Thomas@2359
   760
                                }
Thomas@2359
   761
                            }
Thomas@2359
   762
Thomas@2359
   763
                            // Check if attachment is being opened or if only the preview is needed
Thomas@2359
   764
                            if (CryptableMailItem.PreviewAttachedMailId?.Equals(messageId) != true)
Thomas@2359
   765
                            {
Thomas@2359
   766
                                // Display mirror and cancel opening of original
Thomas@2359
   767
                                cancelOpenEvent = true;
Thomas@2359
   768
                                mirror?.Display();
Thomas@2359
   769
                            }
Thomas@2359
   770
Thomas@2359
   771
                            // Not needed anymore after this point
Thomas@2359
   772
                            CryptableMailItem.PreviewAttachedMailId = null;
Thomas@2359
   773
                        }
Thomas@2359
   774
                    }
Thomas@2359
   775
                    catch (Exception ex)
Thomas@2359
   776
                    {
Thomas@2359
   777
                        messageId = null;
Thomas@2359
   778
                        Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Error checking for attached mail. " + ex.ToString());
Thomas@2359
   779
                    }
Thomas@2359
   780
                }
Thomas@2359
   781
Thomas@2359
   782
                this.cryptableMailItem = new CryptableMailItem(this._CurrentMailItem, provisionalRating);
Thomas@2359
   783
Thomas@2359
   784
                // Set inline response property
Thomas@2359
   785
                this.cryptableMailItem.IsInlineResponse = isInlineResponse;
Thomas@2359
   786
Thomas@2359
   787
                // Set properties for encrypted attached mail
Thomas@2359
   788
                if (isSecureAttachedMail)
Thomas@2359
   789
                {
Thomas@2359
   790
                    this.cryptableMailItem.MessageId = messageId;
Thomas@2359
   791
                    this.cryptableMailItem.IsSecureAttachedMail = true;
Thomas@2359
   792
                }
Thomas@2359
   793
Thomas@2359
   794
                // Connect cryptable mail item events
Thomas@2359
   795
                if (this.cryptableMailItem != null)
Thomas@2359
   796
                {
Thomas@2359
   797
                    // If we don't open the original, set property and return
Thomas@2359
   798
                    if (cancelOpenEvent)
Thomas@2359
   799
                    {
Thomas@2359
   800
                        this.cryptableMailItem.Open += MailItem_Open;
Thomas@2359
   801
                        this.cryptableMailItem.CancelOpen = true;
Thomas@2359
   802
                        return;
Thomas@2359
   803
                    }
Thomas@2359
   804
                    else
Thomas@2359
   805
                    {
Thomas@2359
   806
                        try
Thomas@2359
   807
                        {
Thomas@2359
   808
                            this.cryptableMailItem.PropertyChanged += MailItem_PropertyChanged;
Thomas@2359
   809
                            this.cryptableMailItem.ProcessingCompleted += MailItem_ProcessingCompleted;
Thomas@2359
   810
                            this.cryptableMailItem.GetMirrorCompleted += MailItem_GetMirrorCompleted;
Thomas@2359
   811
                            this.cryptableMailItem.Send += MailItem_Send;
Thomas@2359
   812
Thomas@2359
   813
                            if (this.cryptableMailItem.IsSecurelyStored)
Thomas@2359
   814
                            {
Thomas@2359
   815
                                this.cryptableMailItem.Open += MailItem_Open;
Thomas@2359
   816
                            }
Thomas@2359
   817
                        }
Thomas@2359
   818
                        catch (Exception ex)
Thomas@2359
   819
                        {
Thomas@2359
   820
                            Log.Error("FormRegionPrivacyStatus_FormRegionShowing: Error occured. " + ex.ToString());
Thomas@2359
   821
                        }
Thomas@2359
   822
Thomas@2359
   823
                        if (this._CurrentMailItem.GetIsPEPEnabled())
Thomas@2359
   824
                        {
Thomas@2359
   825
                            // If pEp is enabled, show the form region
Thomas@2359
   826
                            enableFormRegion = true;
Thomas@2359
   827
                        }
Thomas@2359
   828
                        else
Thomas@2359
   829
                        {
Thomas@2359
   830
                            /* If pEp is disabled, process item and show form region in the following cases:
Thomas@2359
   831
                             * 1. Incoming items: if decrypt always option is set
Thomas@2359
   832
                             * 2. Outgoing items: if EnableProtection option is set
Thomas@2359
   833
                             *                    Note: if this property isn't set, subscribe to originally 
Thomas@2359
   834
                             *                          encrypted status update event handler in case the 
Thomas@2359
   835
                             *                          current code runs before CryptableMailItem.MailItem_Reply
Thomas@2359
   836
                             *                          or CryptableMailItem.MailItem_Forward.
Thomas@2359
   837
                             */
Thomas@2359
   838
                            if (this.IsDraft)
Thomas@2359
   839
                            {
Thomas@2359
   840
                                enableFormRegion = true;
Thomas@2359
   841
                                this.cryptableMailItem.OriginallyEncryptedStatusUpdated += CryptableMailItem_OriginallyEncryptedStatusUpdated;
Thomas@2359
   842
                            }
Thomas@2359
   843
                            else
Thomas@2359
   844
                            {
Thomas@2359
   845
                                enableFormRegion = this._CurrentMailItem.GetIsDecryptAlwaysEnabled();
Thomas@2359
   846
                            }
Thomas@2359
   847
                        }
Thomas@2359
   848
                    }
Thomas@2359
   849
                }
Thomas@2359
   850
Thomas@2359
   851
                // Update pEp enabled status
Thomas@2359
   852
                this.SetIsEnabled(enableFormRegion);
Thomas@2359
   853
Thomas@2359
   854
                if (this.isEnabled)
Thomas@2359
   855
                {
Thomas@2359
   856
                    // If forcefully protected, run dedicated decryption
Thomas@2359
   857
                    if (this._CurrentMailItem.GetIsForcefullyProtected())
Thomas@2359
   858
                    {
Thomas@2359
   859
                        FPPMessage fppMessage = new FPPMessage(this._CurrentMailItem);
Thomas@2359
   860
                        if ((fppMessage?.GetMessageType() != null) ||
Thomas@2359
   861
                            (fppMessage?.CurrentMessage?.IsSecure == true))
Thomas@2359
   862
                        {
Thomas@2359
   863
                            fppMessage.ProcessIncoming(true);
Thomas@2359
   864
                        }
Thomas@2359
   865
                        else
Thomas@2359
   866
                        {
Thomas@2359
   867
                            this.TimerRefresh_Tick(null, new EventArgs());
Thomas@2359
   868
                        }
Thomas@2359
   869
                    }
Thomas@2359
   870
                    else
Thomas@2359
   871
                    {
Thomas@2359
   872
                        // Call the timer tick method manually to refresh data with no delay
Thomas@2359
   873
                        this.TimerRefresh_Tick(null, new EventArgs());
Thomas@2359
   874
                    }
Thomas@2359
   875
                }
Thomas@2359
   876
            }
Thomas@2359
   877
            catch (Exception e)
Thomas@2359
   878
            {
Thomas@2359
   879
                Log.Error("Window_SelectionChange: Error. " + e.Message);
Thomas@2359
   880
            }
Thomas@2359
   881
        }
Thomas@2359
   882
Thomas@2359
   883
        /// <summary>
Thomas@2359
   884
        /// Event handler for when the processing is completed in the associated mail item.
Thomas@2359
   885
        /// This will then update the form region UI and the privacy status window as needed.
Thomas@2359
   886
        /// </summary>
Thomas@2359
   887
        private void MailItem_ProcessingCompleted(object sender, MsgProcessor.ProcessingCompletedEventArgs e)
Thomas@2359
   888
        {
Thomas@2359
   889
            Log.Verbose("MailItem_ProcessingComplete: Decryption completed.");
Thomas@2359
   890
Thomas@2359
   891
            try
Thomas@2359
   892
            {
Thomas@2359
   893
                // Marshal code back to UI thread as necessary
Thomas@2359
   894
                KeySyncWizard.Wizard.Dispatcher.Invoke(new Action(() =>
Thomas@2359
   895
                {
Thomas@2359
   896
                    if (this.isEnabled)
Thomas@2359
   897
                    {
Thomas@2359
   898
                        try
Thomas@2359
   899
                        {
Thomas@2359
   900
                            this.SetRating(e.ProcessedRating);
Thomas@2359
   901
Thomas@2359
   902
                            // Set MAPI properties if needed
Thomas@2359
   903
                            if (e.PropertiesToSet?.Count > 0)
Thomas@2359
   904
                            {
Thomas@2359
   905
                                this._CurrentMailItem?.SetMAPIProperties(e.PropertiesToSet);
Thomas@2359
   906
                            }
Thomas@2359
   907
                            Log.Verbose("MailItem_ProcessingComplete: Status bar updated with rating " + Enum.GetName(typeof(pEpRating), e.ProcessedRating));
Thomas@2359
   908
                        }
Thomas@2359
   909
                        catch (Exception ex)
Thomas@2359
   910
                        {
Thomas@2359
   911
                            Log.Verbose("MailItem_ProcessingComplete: Error. " + ex.ToString());
Thomas@2359
   912
                        }
Thomas@2359
   913
Thomas@2359
   914
                        if (repeatProcessing &&
Thomas@2359
   915
                            (repeatCounter++ < maxRepeatCount))
Thomas@2359
   916
                        {
Thomas@2359
   917
                            repeatProcessing = false;
Thomas@2359
   918
                            this.RequestRatingAndUIUpdate();
Thomas@2359
   919
                        }
Thomas@2359
   920
                        else
Thomas@2359
   921
                        {
Thomas@2359
   922
                            /* Check if the mail item is in Outbox and update the inspector window if possible.
Thomas@2359
   923
                             * This is the case when a submitted, but not yet sent email is opened again when working 
Thomas@2359
   924
                             * offline or without internet connection. Without this update, Outlook removes the message class 
Thomas@2359
   925
                             * "IPM.Note.SMIME.MultipartSigned" at the next send event and the message gets invalid and can't be
Thomas@2359
   926
                             * opened again (i.e. is lost).
Thomas@2359
   927
                             */
Thomas@2359
   928
                            try
Thomas@2359
   929
                            {
Thomas@2359
   930
                                if ((this._CurrentMailItem?.GetIsSubmitted() == true) &&
Thomas@2359
   931
                                    (this.IsDraft))
Thomas@2359
   932
                                {
Thomas@2359
   933
                                    UpdateInspector();
Thomas@2359
   934
                                }
Thomas@2359
   935
                            }
Thomas@2359
   936
                            catch (Exception ex)
Thomas@2359
   937
                            {
Thomas@2359
   938
                                Log.Verbose("MailItem_ProcessingComplete: Error while checking if mail item is in outbox or updating inspector. " + ex.Message);
Thomas@2359
   939
                            }
Thomas@2359
   940
Thomas@2359
   941
                            /* Create the unencrypted preview if the mail item is encrypted and
Thomas@2359
   942
                             * it is in an encrypted (untrusted) store
Thomas@2359
   943
                             * 
Thomas@2359
   944
                             * This is done here because FormRegionPrivacyStatus has the cryptable mail item and
Thomas@2359
   945
                             * it also is initialized after FormRegionPreviewUnencrypted.
Thomas@2359
   946
                             */
Thomas@2359
   947
                            try
Thomas@2359
   948
                            {
Thomas@2359
   949
                                if (this.cryptableMailItem.IsSecurelyStored || this.cryptableMailItem.IsSecureAttachedMail)
Thomas@2359
   950
                                {
Thomas@2359
   951
                                    Log.Verbose("MailItem_ProcessingComplete: Starting mirror location.");
Thomas@2359
   952
                                    this.cryptableMailItem.StartGetMirror(this.cryptableMailItem.MessageId);
Thomas@2359
   953
                                }
Thomas@2359
   954
                                else
Thomas@2359
   955
                                {
Thomas@2359
   956
                                    this.SetNote();
Thomas@2359
   957
                                }
Thomas@2359
   958
                            }
Thomas@2359
   959
                            catch (Exception ex)
Thomas@2359
   960
                            {
Thomas@2359
   961
                                // Error is possible in some situations where the mail item was deleted or moved while decryption was ongoing.
Thomas@2359
   962
                                // While rare, just log the issue and stop the process
Thomas@2359
   963
                                Log.Warning("MailItem_ProcessingComplete: Failed to start mirror location, " + ex.ToString());
Thomas@2359
   964
                            }
Thomas@2359
   965
Thomas@2359
   966
                            /* OUT-470: Workaround until this is implemented in the engine:
Thomas@2359
   967
                             * Only enable Force Protection if all recipients are grey
Thomas@2359
   968
                             */
Thomas@2359
   969
                            if (this.IsDraft)
Thomas@2359
   970
                            {
Thomas@2359
   971
                                bool disableForceProtection = false;
Thomas@2359
   972
                                Outlook.Recipients recipients = null;
Thomas@2359
   973
                                Outlook.Recipient recipient = null;
Thomas@2359
   974
                                PEPIdentity pEpIdentity = null;
Thomas@2359
   975
Thomas@2359
   976
                                try
Thomas@2359
   977
                                {
Thomas@2359
   978
                                    recipients = this._CurrentMailItem?.Recipients;
Thomas@2359
   979
                                    if (recipients?.Count > 0)
Thomas@2359
   980
                                    {
Thomas@2359
   981
                                        for (int i = 1; i <= recipients.Count; i++)
Thomas@2359
   982
                                        {
Thomas@2359
   983
                                            recipient = recipients[i];
Thomas@2359
   984
                                            if ((PEPIdentity.Create(recipient, out pEpIdentity, false) == Globals.ReturnStatus.Success) &&
Thomas@2359
   985
                                                ((PEPIdentity.GetIsOwnIdentity(pEpIdentity.Address) ||
Thomas@2359
   986
                                                 (ThisAddIn.PEPEngine.IdentityRating(pEpIdentity.ToCOMType()) >= pEpRating.pEpRatingReliable))))
Thomas@2359
   987
                                            {
Thomas@2359
   988
                                                disableForceProtection = true;
Thomas@2359
   989
                                                Log.Verbose("ToggleButtonForceProtection_GetEnabled: Secure recipient found. Disabling force protection.");
Thomas@2359
   990
                                                break;
Thomas@2359
   991
                                            }
Thomas@2359
   992
                                        }
Thomas@2359
   993
                                    }
Thomas@2359
   994
                                    else
Thomas@2359
   995
                                    {
Thomas@2359
   996
                                        // If there aren't any recipients (anymore), reset values
Thomas@2359
   997
                                        this.DisableForceProtection = false;
Thomas@2359
   998
                                        this.ForceProtection = false;
Thomas@2359
   999
                                        this.NeverUnsecure = false;
Thomas@2359
  1000
                                        this.ForceUnencrypted = false;
Thomas@2359
  1001
                                    }
Thomas@2359
  1002
                                }
Thomas@2359
  1003
                                catch (Exception ex)
Thomas@2359
  1004
                                {
Thomas@2359
  1005
                                    Log.Error("ToggleButtonForceProtection_GetEnabled: Error occured. " + ex.ToString());
Thomas@2359
  1006
                                }
Thomas@2359
  1007
                                finally
Thomas@2359
  1008
                                {
Thomas@2359
  1009
                                    recipient = null;
Thomas@2359
  1010
                                    recipients = null;
Thomas@2359
  1011
                                }
Thomas@2359
  1012
Thomas@2359
  1013
                                this.DisableForceProtection = disableForceProtection;
Thomas@2359
  1014
                            }
Thomas@2359
  1015
                        }
Thomas@2359
  1016
                    }
Thomas@2359
  1017
                }));
Thomas@2359
  1018
            }
Thomas@2359
  1019
            catch (Exception ex)
Thomas@2359
  1020
            {
Thomas@2359
  1021
                Log.Error("MailItem_ProcessingComplete: Error setting UI state, " + ex.ToString());
Thomas@2359
  1022
            }
Thomas@2359
  1023
Thomas@2359
  1024
            this.processingOngoing = false;
Thomas@2359
  1025
        }
Thomas@2359
  1026
Thomas@2359
  1027
        /// <summary>
Thomas@2359
  1028
        /// Event handler for when the get mirror locating process is complete for the associated mail item.
Thomas@2359
  1029
        /// This will then update the unencrypted preview in the UI.
Thomas@2359
  1030
        /// </summary>
Thomas@2359
  1031
        private void MailItem_GetMirrorCompleted(object sender, CryptableMailItem.GetMirrorCompletedEventArgs e)
Thomas@2359
  1032
        {
Thomas@2359
  1033
            try
Thomas@2359
  1034
            {
Thomas@2359
  1035
                // Marshal code back to UI thread as necessary
Thomas@2359
  1036
                KeySyncWizard.Wizard.Dispatcher.Invoke(new Action(() =>
Thomas@2359
  1037
                {
Thomas@2359
  1038
                    if (this.isEnabled)
Thomas@2359
  1039
                    {
Thomas@2359
  1040
                        // If the message was forcefully protected, there is no mirror and we show the actual message
Thomas@2359
  1041
                        if ((e.Mirror == null) &&
Thomas@2359
  1042
                            (this._CurrentMailItem?.GetIsForcefullyProtected() == true))
Thomas@2359
  1043
                        {
Thomas@2359
  1044
                            PEPMessage mirror = null;
Thomas@2359
  1045
                            if (PEPMessage.Create(this._CurrentMailItem, out mirror) == Globals.ReturnStatus.Success)
Thomas@2359
  1046
                            {
Thomas@2359
  1047
                                e.Mirror = mirror;
Thomas@2359
  1048
                            }
Thomas@2359
  1049
                        }
Thomas@2359
  1050
Thomas@2359
  1051
                        if ((e.Mirror == null) &&
Thomas@2359
  1052
                            (this.cryptableMailItem.LastProcessedStatus == Globals.ReturnStatus.Failure))
Thomas@2359
  1053
                        {
Thomas@2359
  1054
                            this.SetNote(Properties.Resources.Message_OpenError);
Thomas@2359
  1055
                            Log.Verbose("MailItem_GetMirrorComplete: Cannot display mirror, failure during decryption.");
Thomas@2359
  1056
                        }
Thomas@2359
  1057
                        else if ((e.Mirror == null) &&
Thomas@2359
  1058
                                 (this.cryptableMailItem.LastProcessedStatus == Globals.ReturnStatus.FailureNoConnection))
Thomas@2359
  1059
                        {
Thomas@2359
  1060
                            this.SetNote(Properties.Resources.Message_DecryptionNoConnection);
Thomas@2359
  1061
                            Log.Verbose("MailItem_GetMirrorComplete: Cannot display mirror, connection failure during decryption.");
Thomas@2359
  1062
                        }
Thomas@2359
  1063
                        else
Thomas@2359
  1064
                        {
Thomas@2360
  1065
                            /* We have to find out here if the window is an explorer or an inspector.
Thomas@2360
  1066
                             * Calling Globals.FormRegions[] with an ambiguous window type leads to a crash.
Thomas@2360
  1067
                             */
Thomas@2360
  1068
                            Outlook.Explorer explorer;
Thomas@2360
  1069
                            Outlook.Inspector inspector;
Thomas@2360
  1070
                            WindowFormRegionCollection formRegions = null;
Thomas@2360
  1071
                            try
Thomas@2359
  1072
                            {
Thomas@2360
  1073
                                explorer = this.Window as Outlook.Explorer;
Thomas@2360
  1074
                                if (explorer != null)
Thomas@2359
  1075
                                {
Thomas@2360
  1076
                                    formRegions = Globals.FormRegions[explorer];
Thomas@2359
  1077
                                }
Thomas@2360
  1078
                                else
Thomas@2360
  1079
                                {
Thomas@2360
  1080
                                    inspector = this.Window as Outlook.Inspector;
Thomas@2360
  1081
                                    formRegions = Globals.FormRegions[inspector];
Thomas@2360
  1082
                                }
Thomas@2360
  1083
                            }
Thomas@2360
  1084
                            catch (Exception ex)
Thomas@2360
  1085
                            {
Thomas@2360
  1086
                                formRegions = null;
Thomas@2360
  1087
                                Log.Error("MailItem_GetMirrorCompleted: Error getting form regions collection. " + ex.ToString());
Thomas@2360
  1088
                            }
Thomas@2360
  1089
                            finally
Thomas@2360
  1090
                            {
Thomas@2360
  1091
                                explorer = null;
Thomas@2360
  1092
                                inspector = null;
Thomas@2360
  1093
                            }
Thomas@2360
  1094
Thomas@2360
  1095
                            // If we have a FormRegionPreviewUnencrypted and it's visible, show preview
Thomas@2360
  1096
                            if (formRegions?.FormRegionPreviewUnencrypted?.Visible == true)
Thomas@2360
  1097
                            {
Thomas@2360
  1098
                                formRegions.FormRegionPreviewUnencrypted.DisplayState.OriginalEntryId = this._CurrentMailItem?.EntryID;
Thomas@2360
  1099
                                formRegions.FormRegionPreviewUnencrypted.DisplayState.SetMessage(e.Mirror);
Thomas@2359
  1100
Thomas@2359
  1101
                                Log.Verbose("MailItem_GetMirrorComplete: Mirror found and displayed.");
Thomas@2359
  1102
                            }
Thomas@2360
  1103
                            else
Thomas@2360
  1104
                            {
Thomas@2360
  1105
                                Log.Error("MailItem_GetMirrorComplete: FormRegionPreviewUnencrypted is null or invisible.");
Thomas@2360
  1106
                            }
Thomas@2359
  1107
                        }
Thomas@2359
  1108
Thomas@2359
  1109
                        // Display the mirror if necessary
Thomas@2359
  1110
                        if ((this.cryptableMailItem != null) &&
Thomas@2359
  1111
                            (this.displayMirrorRequested))
Thomas@2359
  1112
                        {
Thomas@2359
  1113
                            this.cryptableMailItem.DisplayMirror();
Thomas@2359
  1114
                            this.displayMirrorRequested = false;
Thomas@2359
  1115
                        }
Thomas@2359
  1116
                    }
Thomas@2359
  1117
                }));
Thomas@2359
  1118
            }
Thomas@2359
  1119
            catch (Exception ex)
Thomas@2359
  1120
            {
Thomas@2359
  1121
                Log.Error("MailItem_GetMirrorComplete: Error displaying preview, " + ex.ToString());
Thomas@2359
  1122
            }
Thomas@2359
  1123
        }
Thomas@2359
  1124
Thomas@2359
  1125
        /// <summary>
Thomas@2359
  1126
        /// Event handler for the mail item originally encrypted status updated.
Thomas@2359
  1127
        /// This event is fired after the status has been updated with parent information following a
Thomas@2359
  1128
        /// forward or reply mail item event (on a different, likely parent, mail item).
Thomas@2359
  1129
        /// </summary>
Thomas@2359
  1130
        protected void CryptableMailItem_OriginallyEncryptedStatusUpdated(object sender, EventArgs e)
Thomas@2359
  1131
        {
Thomas@2359
  1132
            // Process the mail item now that the cache is updated
Thomas@2359
  1133
            if (this.cryptableMailItem.IsOriginallyEncrypted)
Thomas@2359
  1134
            {
Thomas@2359
  1135
                this.cryptableMailItem.StartProcessing();
Thomas@2359
  1136
            }
Thomas@2359
  1137
        }
Thomas@2359
  1138
Thomas@2359
  1139
        /// <summary>
Thomas@2359
  1140
        /// Event handler for when a mail item is being opened in an inspector.
Thomas@2359
  1141
        /// See: https://msdn.microsoft.com/en-us/library/office/ff865989.aspx
Thomas@2359
  1142
        /// </summary>
Thomas@2359
  1143
        /// <param name="cancel">Whether to cancel the event: Value is False when the event occurs. 
Thomas@2359
  1144
        /// If the event procedure sets this argument to True, the open operation is not completed 
Thomas@2359
  1145
        /// and the inspector is not displayed.</param>
Thomas@2359
  1146
        protected void MailItem_Open(ref bool cancel)
Thomas@2359
  1147
        {
Thomas@2359
  1148
            bool result;
Thomas@2359
  1149
Thomas@2359
  1150
            if ((this.isEnabled) &&
Thomas@2359
  1151
                (this.cryptableMailItem != null))
Thomas@2359
  1152
            {
Thomas@2359
  1153
                // If cryptable mail item is not to be opened, cancel opening
Thomas@2359
  1154
                if (this.cryptableMailItem.CancelOpen)
Thomas@2359
  1155
                {
Thomas@2359
  1156
                    cancel = true;
Thomas@2359
  1157
                }
Thomas@2359
  1158
                else if ((this.cryptableMailItem.IsSecurelyStored) &&
Thomas@2359
  1159
                         (this.cryptableMailItem.IsIncoming || this.cryptableMailItem.IsOriginallyEncrypted || !this.cryptableMailItem.IsDraft))
Thomas@2359
  1160
                {
Thomas@2359
  1161
                    // Try to open the mirror
Thomas@2359
  1162
                    result = this.cryptableMailItem.DisplayMirror();
Thomas@2359
  1163
Thomas@2359
  1164
                    if (result == false)
Thomas@2359
  1165
                    {
Thomas@2359
  1166
                        // Set flag to open after decryption/mirror location
Thomas@2359
  1167
                        this.displayMirrorRequested = true;
Thomas@2359
  1168
                    }
Thomas@2359
  1169
Thomas@2359
  1170
                    // Always cancel opening the original
Thomas@2359
  1171
                    cancel = true;
Thomas@2359
  1172
                }
Thomas@2359
  1173
            }
Thomas@2359
  1174
        }
Thomas@2359
  1175
Thomas@2359
  1176
        /// <summary>
Thomas@2359
  1177
        /// Event handler for when a mail item is sent.
Thomas@2359
  1178
        /// See: https://msdn.microsoft.com/en-us/library/office/ff865379.aspx
Thomas@2359
  1179
        /// </summary>
Thomas@2359
  1180
        /// <param name="cancel">Whether to cancel the event: Value is False when the event occurs. 
Thomas@2359
  1181
        /// If the event procedure sets this argument to True, the send operation is not completed 
Thomas@2359
  1182
        /// and the inspector is left open.</param>
Thomas@2359
  1183
        protected void MailItem_Send(ref bool cancel)
Thomas@2359
  1184
        {
Thomas@2359
  1185
            DialogResult result;
Thomas@2359
  1186
Thomas@2359
  1187
            if (this.isEnabled)
Thomas@2359
  1188
            {
Thomas@2359
  1189
                if ((this.cryptableMailItem.IsBeingProcessed) ||
Thomas@2359
  1190
                    (this.processingOngoing))
Thomas@2359
  1191
                {
Thomas@2359
  1192
                    Log.Verbose("MailItem_Send cancelled. Mail item still being processed.");
Thomas@2359
  1193
                    cancel = true;
Thomas@2359
  1194
                    return;
Thomas@2359
  1195
                }
Thomas@2359
  1196
Thomas@2359
  1197
                // Show warning message if needed
Thomas@2359
  1198
                if ((Globals.ThisAddIn.Settings.IsSecurityLossWarningEnabled) &&
Thomas@2359
  1199
                    (this.Rating < pEpRating.pEpRatingUnreliable) &&
Thomas@2359
  1200
                    (this.cryptableMailItem.IsOriginallyEncrypted))
Thomas@2359
  1201
                {
Thomas@2359
  1202
Thomas@2359
  1203
#if READER_RELEASE_MODE
Thomas@2359
  1204
                    FormReaderSplash warningMessage = new FormReaderSplash(true);
Thomas@2359
  1205
                    result = warningMessage.ShowDialog();
Thomas@2359
  1206
Thomas@2359
  1207
                    if (result != DialogResult.OK)
Thomas@2359
  1208
                    {
Thomas@2359
  1209
                        // Cancel sending
Thomas@2359
  1210
                        cancel = true;
Thomas@2359
  1211
                    }
Thomas@2359
  1212
#else
Thomas@2359
  1213
                    result = MessageBox.Show(Properties.Resources.Message_WarningSecurityLoss,
Thomas@2359
  1214
                                             Properties.Resources.Message_TitleConfirmOperation,
Thomas@2359
  1215
                                             MessageBoxButtons.YesNo,
Thomas@2359
  1216
                                             MessageBoxIcon.Warning);
Thomas@2359
  1217
Thomas@2359
  1218
                    if (result == DialogResult.No)
Thomas@2359
  1219
                    {
Thomas@2359
  1220
                        // Cancel sending
Thomas@2359
  1221
                        cancel = true;
Thomas@2359
  1222
                    }
Thomas@2359
  1223
#endif
Thomas@2359
  1224
                }
Thomas@2359
  1225
Thomas@2359
  1226
                if (cancel == false)
Thomas@2359
  1227
                {
Thomas@2359
  1228
                    // Set pEp options if needed
Thomas@2359
  1229
                    if ((this.ForceProtection) &&
Thomas@2359
  1230
                        (this.DisableForceProtection == false))
Thomas@2359
  1231
                    {
Thomas@2359
  1232
                        this._CurrentMailItem?.SetPEPProperty(MailItemExtensions.PEPProperty.ForceProtection, Guid.NewGuid().ToString());
Thomas@2359
  1233
                    }
Thomas@2359
  1234
                    else if (this.ForceUnencrypted)
Thomas@2359
  1235
                    {
Thomas@2359
  1236
                        this._CurrentMailItem?.SetPEPProperty(MailItemExtensions.PEPProperty.ForceUnencrypted, true);
Thomas@2359
  1237
                    }
Thomas@2359
  1238
Thomas@2359
  1239
                    if (this.NeverUnsecure)
Thomas@2359
  1240
                    {
Thomas@2359
  1241
                        this._CurrentMailItem?.SetPEPProperty(MailItemExtensions.PEPProperty.NeverUnsecure, true);
Thomas@2359
  1242
                    }
Thomas@2359
  1243
Thomas@2359
  1244
                    // Stop and disconnect the refresh timer
Thomas@2359
  1245
                    // This is necessary so an ongoing refresh doesn't try to access a mail item as it's being moved
Thomas@2359
  1246
                    this.TimerRefresh.Stop();
Thomas@2359
  1247
                    this.TimerRefresh.Enabled = false;
Thomas@2359
  1248
                    this.TimerRefresh.Tick -= TimerRefresh_Tick;
Thomas@2359
  1249
                }
Thomas@2359
  1250
            }
Thomas@2359
  1251
        }
Thomas@2359
  1252
Thomas@2359
  1253
        /// <summary>
Thomas@2359
  1254
        /// Event handler for when a mail item property is changed.
Thomas@2359
  1255
        /// See: https://msdn.microsoft.com/en-us/library/office/ff866739.aspx
Thomas@2359
  1256
        /// </summary>
Thomas@2359
  1257
        /// <param name="propertyName">The name of the property that was changed.</param>
Thomas@2359
  1258
        protected void MailItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
Thomas@2359
  1259
        {
Thomas@2359
  1260
            switch (e.PropertyName.ToUpperInvariant())
Thomas@2359
  1261
            {
Thomas@2359
  1262
                case "BCC":
Thomas@2359
  1263
                    {
Thomas@2359
  1264
                        // Outlook always fires Bcc, Cc and To together so only "TO" is used
Thomas@2359
  1265
                        break;
Thomas@2359
  1266
                    }
Thomas@2359
  1267
                case "CC":
Thomas@2359
  1268
                    {
Thomas@2359
  1269
                        // Outlook always fires Bcc, Cc and To together so only "TO" is used
Thomas@2359
  1270
                        break;
Thomas@2359
  1271
                    }
Thomas@2359
  1272
                case "SENTONBEHALFOFNAME":
Thomas@2359
  1273
                    {
Thomas@2359
  1274
                        // Always fired with "SENDUSINGACCOUNT" so is ignored
Thomas@2359
  1275
                        break;
Thomas@2359
  1276
                    }
Thomas@2359
  1277
                case "SENDUSINGACCOUNT":
Thomas@2359
  1278
                    {
Thomas@2359
  1279
                        // Update pEp enabled status
Thomas@2359
  1280
                        this.isStarted = false;
Thomas@2359
  1281
                        this.SetIsEnabled((this.CurrentMailItem)?.GetEnableFormRegion() ?? false);
Thomas@2359
  1282
Thomas@2359
  1283
                        // Refresh the UI
Thomas@2359
  1284
                        this.ResolveAllRecipients();
Thomas@2359
  1285
                        this.RequestRatingAndUIUpdate();
Thomas@2359
  1286
                        RibbonCustomizations.Invalidate();
Thomas@2359
  1287
Thomas@2359
  1288
                        break;
Thomas@2359
  1289
                    }
Thomas@2359
  1290
                case "TO":
Thomas@2359
  1291
                    {
Thomas@2359
  1292
                        if (this.isEnabled)
Thomas@2359
  1293
                        {
Thomas@2359
  1294
                            this.RequestRatingAndUIUpdate();
Thomas@2359
  1295
                        }
Thomas@2359
  1296
                        break;
Thomas@2359
  1297
                    }
Thomas@2359
  1298
            }
Thomas@2359
  1299
        }
Thomas@2359
  1300
Thomas@2359
  1301
        /// <summary>
Thomas@2359
  1302
        /// Event handler for when a handshake dialog was updated.
Thomas@2359
  1303
        /// </summary>
Thomas@2359
  1304
        protected void HandshakeDialog_Updated(object sender, EventArgs e)
Thomas@2359
  1305
        {
Thomas@2359
  1306
            // Update current form region
Thomas@2359
  1307
            this.RequestRatingAndUIUpdate();
Thomas@2360
  1308
Thomas@2359
  1309
            /* If a handshake is performed while having the same message open both in an inspector
Thomas@2359
  1310
             * and an Window window, the one that didn't trigger the handshake won't get updated
Thomas@2359
  1311
             * automatically. Therefore, after a handshake, we also update all other open windows.
Thomas@2359
  1312
             */
Thomas@2359
  1313
            try
Thomas@2359
  1314
            {
Thomas@2360
  1315
                Globals.ThisAddIn.RecalculateAllWindows(this);
Thomas@2359
  1316
            }
Thomas@2359
  1317
            catch (Exception ex)
Thomas@2359
  1318
            {
Thomas@2359
  1319
                Log.Error("HandshakeDialog_Updated: Error updating other windows. " + ex.Message);
Thomas@2359
  1320
            }
Thomas@2359
  1321
        }
Thomas@2359
  1322
Thomas@2359
  1323
        /// <summary>
Thomas@2359
  1324
        /// Event handler for when a handshake dialog was closed.
Thomas@2359
  1325
        /// </summary>
Thomas@2359
  1326
        protected void HandshakeDialog_Closed(object sender, EventArgs e)
Thomas@2359
  1327
        {
Thomas@2359
  1328
            if (this.handshakeDialog != null)
Thomas@2359
  1329
            {
Thomas@2359
  1330
                this.handshakeDialog.OnUpdateStatus -= HandshakeDialog_Updated;
Thomas@2359
  1331
                this.handshakeDialog.Closed -= HandshakeDialog_Closed;
Thomas@2359
  1332
                this.handshakeDialog = null;
Thomas@2359
  1333
            }
Thomas@2359
  1334
        }
Thomas@2359
  1335
Thomas@2359
  1336
        /// <summary>
Thomas@2359
  1337
        /// Event handler called after the refresh timer has elapsed.
Thomas@2359
  1338
        /// </summary>
Thomas@2359
  1339
        private void TimerRefresh_Tick(object sender, EventArgs e)
Thomas@2359
  1340
        {
Thomas@2359
  1341
            bool tryAgain = false;
Thomas@2359
  1342
#pragma warning disable 219
Thomas@2359
  1343
            bool markForDownload = false;
Thomas@2359
  1344
#pragma warning restore 219
Thomas@2359
  1345
            this.TimerRefresh.Enabled = false; // Only once
Thomas@2359
  1346
            Outlook.OlDownloadState dlState;
Thomas@2359
  1347
Thomas@2359
  1348
            /* The Refresh/UI_Update process:
Thomas@2359
  1349
             * There are the following components:
Thomas@2359
  1350
             *   1. TimerRefresh_Tick
Thomas@2359
  1351
             *        This is the main timer tick event handler called any time
Thomas@2359
  1352
             *        a refresh was requested (RequestRatingAndUIUpdate) and hasn't been run yet. 
Thomas@2359
  1353
             *        A refresh is requested either at initialization or when a property changes
Thomas@2359
  1354
             *        (such as MailItem_PropertyChanged). It is on a timer as many 
Thomas@2359
  1355
             *        property change events could occur rapidy, but only one refresh should
Thomas@2359
  1356
             *        occur for performance reasons.
Thomas@2359
  1357
             * 
Thomas@2359
  1358
             *   2. ImmediateRatingAndUIUpdate
Thomas@2359
  1359
             *        This will re-calculate the mail item's rating.
Thomas@2359
  1360
             *        This internally just calls CryptableMailItem.StartProcessing.
Thomas@2359
  1361
             * 
Thomas@2359
  1362
             *   3. MailItem_ProcessingCompleted
Thomas@2359
  1363
             *        When processing of the mail item is complete, this even handler will be called.
Thomas@2359
  1364
             *        This will update the UI with the latest rating then call StartGetMirror.
Thomas@2359
  1365
             *        The CopyStateToUI method is used which means any open privacy status form will also
Thomas@2359
  1366
             *        be updated.
Thomas@2359
  1367
             * 
Thomas@2359
  1368
             *   4. MailItem_GetMirrorComplete
Thomas@2359
  1369
             *        This is the final step in updating the UI, after a mirror is located, it's contents
Thomas@2359
  1370
             *        will be shown in the unencrypted preview.
Thomas@2359
  1371
             * 
Thomas@2359
  1372
             * The general calling sequence is as shown above 1->4 with each component calling the next.
Thomas@2359
  1373
             * However, for methods that update the mail item directly, commonly only 2->4 is needed.
Thomas@2359
  1374
             */
Thomas@2359
  1375
Thomas@2359
  1376
            // Ensure the tick method is not called more than once
Thomas@2359
  1377
            if ((this.isEnabled) &&
Thomas@2359
  1378
                (refreshOngoing == false))
Thomas@2359
  1379
            {
Thomas@2359
  1380
                this.refreshOngoing = true;
Thomas@2359
  1381
Thomas@2359
  1382
                if ((this.cryptableMailItem != null) &&
Thomas@2359
  1383
                    (this.cryptableMailItem.IsBeingProcessed == false))
Thomas@2359
  1384
                {
Thomas@2359
  1385
                    // Attempt to get the download state
Thomas@2359
  1386
                    try
Thomas@2359
  1387
                    {
Thomas@2359
  1388
                        dlState = this.cryptableMailItem.DownloadState;
Thomas@2359
  1389
                    }
Thomas@2359
  1390
                    catch (Exception ex)
Thomas@2359
  1391
                    {
Thomas@2359
  1392
                        Log.Warning("TimerRefresh_Tick: Get DownloadState failed, " + ex.ToString());
Thomas@2359
  1393
Thomas@2359
  1394
                        // Assume everything is downloaded, but try to download again as well
Thomas@2359
  1395
                        dlState = Outlook.OlDownloadState.olFullItem;
Thomas@2359
  1396
                        markForDownload = true;
Thomas@2359
  1397
                    }
Thomas@2359
  1398
Thomas@2359
  1399
                    if (dlState == Outlook.OlDownloadState.olFullItem)
Thomas@2359
  1400
                    {
Thomas@2359
  1401
                        this.ImmediateRatingAndUIUpdate();
Thomas@2359
  1402
                    }
Thomas@2359
  1403
                    else
Thomas@2359
  1404
                    {
Thomas@2359
  1405
                        markForDownload = true;
Thomas@2359
  1406
                    }
Thomas@2359
  1407
Thomas@2359
  1408
                    /* 12/16/2016: It could be verified via testing that setting the MarkForDownload property
Thomas@2359
  1409
                     * can be a way to crash Outlook under certain circumstances (e.g. with IMAP on Outlook 2010 or on Windows 7). 
Thomas@2359
  1410
                     * This then is not caught by a try/catch block and therefore has to be considered an Outlook bug.
Thomas@2359
  1411
                     * It seems that in newer versions of Outlook/Windows, they fixed it, causing exceptions, if at all.
Thomas@2359
  1412
                     * For now, the following is commented out to prevent a crash. If at any point we see that header-only
Thomas@2359
  1413
                     * messages cause bigger issues, this decision has to be reevaluated.
Thomas@2359
  1414
                     */
Thomas@2359
  1415
                    //if (markForDownload)
Thomas@2359
  1416
                    //{
Thomas@2359
  1417
                    //    // Try to mark the message for full download
Thomas@2359
  1418
                    //    try
Thomas@2359
  1419
                    //    {
Thomas@2359
  1420
                    //        this.cryptableMailItem.MarkForDownload = Outlook.OlRemoteStatus.olMarkedForDownload;
Thomas@2359
  1421
                    //        tryAgain = true;
Thomas@2359
  1422
                    //    }
Thomas@2359
  1423
                    //    catch (Exception ex)
Thomas@2359
  1424
                    //    {
Thomas@2359
  1425
                    //        Log.Warning("TimerRefresh_Tick: MarkForDownload failed, " + ex.ToString());
Thomas@2359
  1426
                    //    }
Thomas@2359
  1427
                    //}
Thomas@2359
  1428
                }
Thomas@2359
  1429
                else
Thomas@2359
  1430
                {
Thomas@2359
  1431
                    repeatProcessing = true;
Thomas@2359
  1432
                }
Thomas@2359
  1433
Thomas@2359
  1434
                // Set the timer to refresh again later automatically
Thomas@2359
  1435
                if (tryAgain)
Thomas@2359
  1436
                {
Thomas@2359
  1437
                    this.TimerRefresh.Interval = 100;
Thomas@2359
  1438
                    this.TimerRefresh.Enabled = true;
Thomas@2359
  1439
                }
Thomas@2359
  1440
Thomas@2359
  1441
                this.refreshOngoing = false;
Thomas@2359
  1442
            }
Thomas@2359
  1443
        }
Thomas@2359
  1444
Thomas@2359
  1445
        #endregion
Thomas@2359
  1446
    }
Thomas@2359
  1447
}