UI/FormRegionPrivacyStatus.cs
author Dean Looyengoed
Thu, 31 Mar 2016 23:14:58 +0200
changeset 747 15680ce2f148
parent 740 cc736d688b23
child 758 cc240ea6d62b
permissions -rw-r--r--
Check for and log error that occurs when deleting an item that is being decrypted.
Dean@159
     1
´╗┐using pEpCOMServerAdapterLib;
Dean@159
     2
using System;
vb@133
     3
using System.Collections.Generic;
Dean@445
     4
using System.ComponentModel;
Dean@438
     5
using System.Drawing;
Dean@159
     6
using System.Runtime.InteropServices;
vb@133
     7
using System.Windows.Forms;
Dean@159
     8
using Color = System.Drawing.Color;
vb@133
     9
using Outlook = Microsoft.Office.Interop.Outlook;
vb@133
    10
vb@133
    11
namespace pEp
vb@133
    12
{
Dean@159
    13
    /// <summary>
Dean@312
    14
    /// Partial class for the privacy status form region that is displayed below every outlook message.
Dean@159
    15
    /// </summary>
Dean@312
    16
    partial class FormRegionPrivacyStatus
vb@133
    17
    {
vb@133
    18
        #region Form Region Factory
vb@133
    19
vb@133
    20
        [Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Note)]
Dean@312
    21
        [Microsoft.Office.Tools.Outlook.FormRegionName("pEp.FormRegionPrivacyStatus")]
Dean@312
    22
        public partial class FormRegionPrivacyStatusFactory
vb@133
    23
        {
vb@133
    24
            // Occurs before the form region is initialized.
vb@133
    25
            // To prevent the form region from appearing, set e.Cancel to true.
vb@133
    26
            // Use e.OutlookItem to get a reference to the current Outlook item.
Dean@312
    27
            private void FormRegionPrivacyStatus_FormRegionInitializing(object sender, Microsoft.Office.Tools.Outlook.FormRegionInitializingEventArgs e)
vb@133
    28
            {
Dean@327
    29
                WindowFormRegionCollection formRegions;
Dean@327
    30
Dean@327
    31
                /* There is a Microsoft bug at least in Outlook 2013 and Windows 8.1
Dean@327
    32
                 * This bug causes multiple PrivacyStatus form regions to appear stacked on top of each other.
Dean@327
    33
                 * To trigger this bug, on an unencrypted server, click reply to compose an in-line response.
Dean@327
    34
                 * Then click to another tab such as People or Tasks. Then click back on the mail tab to view 
Dean@327
    35
                 * the original email again. Two form regions will be visible: 
Dean@327
    36
                 * (1) for the status during the in-line reply and 
Dean@327
    37
                 * (2) for the status of only the received message.
Dean@327
    38
                 * 
Dean@327
    39
                 * To fix this bug, any existing form regions are found and closed when initializing a new privacy status
Dean@327
    40
                 * form region.
Dean@327
    41
                 */
Dean@327
    42
Dean@327
    43
                try
Dean@327
    44
                {
Dean@327
    45
                    formRegions = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveExplorer()];
Dean@327
    46
                    if (formRegions.FormRegionPrivacyStatus != null)
Dean@327
    47
                    {
Dean@327
    48
                        /* Note: there seems to be no way to actually close the form region.
Dean@327
    49
                         * Therefore, this is as close as possible to actually closing it.
Dean@327
    50
                         * The actual form regions will be cleaned up as soon as another email is selected.
Dean@327
    51
                         */
Dean@327
    52
                        formRegions.FormRegionPrivacyStatus.OutlookFormRegion.Visible = false;
Dean@327
    53
                    }
Dean@327
    54
                }
Dean@327
    55
                catch { }
Dean@327
    56
Dean@327
    57
                return;
vb@133
    58
            }
vb@133
    59
        }
vb@133
    60
vb@133
    61
        #endregion
vb@133
    62
Dean@159
    63
        /* Notes:
Dean@179
    64
         * 
Dean@159
    65
         * Use this.OutlookItem to get a reference to the current Outlook item.
Dean@159
    66
         * Use this.OutlookFormRegion to get a reference to the form region.
Dean@179
    67
         * 
Dean@179
    68
         * UI State Managment:
Dean@179
    69
         * 
Dean@179
    70
         * The UI state is almost entirely set from the associated mail item data.
Dean@179
    71
         * However, a separate state class is maintained to represent the UI as some separation is needed.
Dean@179
    72
         * This logical separation MUST be maintained throughout the code.
Dean@179
    73
         * Specific cases are noted where possible.
Dean@179
    74
         * 
Dean@356
    75
         * The separate privacy status manager form state is also managed here.
Dean@259
    76
         * 
Dean@159
    77
         */
Dean@159
    78
Dean@680
    79
        private CryptableMailItem       associatedMailItem = null;
Dean@680
    80
        private bool                    eventsAreConnected = false;
Dean@680
    81
        private bool                    initialized        = false;
Dean@680
    82
        private FormManagePrivacyStatus managerForm        = null;
Dean@680
    83
        private bool                    refreshOngoing     = false;
Dean@259
    84
Dean@250
    85
        // Data or controls not stored in the UI
Dean@179
    86
        private _pEp_color stateUIColorRating; // WARNING: Do NOT use this directly
vb@133
    87
Dean@159
    88
        /**************************************************************
Dean@159
    89
         * 
Dean@159
    90
         * Methods
Dean@159
    91
         * 
Dean@159
    92
         *************************************************************/
Dean@159
    93
Dean@171
    94
        /// <summary>
Dean@438
    95
        /// Determines if this form region is running in an inspector window.
Dean@438
    96
        /// If not true, it is assumed to be within an explorer window.
Dean@438
    97
        /// </summary>
Dean@438
    98
        /// <returns>True if an inspector window, false if within an explorer.</returns>
Dean@438
    99
        private bool IsWithinInspector()
Dean@438
   100
        {
Dean@438
   101
            bool isWithinInspector = false;
Dean@438
   102
            Outlook.Explorer temp = null;
Dean@438
   103
Dean@438
   104
            try
Dean@438
   105
            {
Dean@438
   106
                // Just try to cast to an explorer class
Dean@438
   107
                temp = (Outlook.Explorer)this.OutlookFormRegion.Parent;
Dean@438
   108
                isWithinInspector = false;
Dean@438
   109
            }
Dean@438
   110
            catch
Dean@438
   111
            {
Dean@438
   112
                isWithinInspector = true;
Dean@438
   113
            }
Dean@438
   114
            finally
Dean@438
   115
            {
Dean@438
   116
                if (temp != null)
Dean@438
   117
                {
Dean@438
   118
                    Marshal.ReleaseComObject(temp);
Dean@438
   119
                    temp = null;
Dean@438
   120
                }
Dean@438
   121
            }
Dean@438
   122
Dean@438
   123
            return (isWithinInspector);
Dean@438
   124
        }
Dean@438
   125
Dean@438
   126
        /// <summary>
Dean@170
   127
        /// Sets the cryptable mail item associated with this encryption status panel.
Dean@170
   128
        /// The associated mail item can then be accessed through its local variable.
Dean@170
   129
        /// </summary>
Dean@170
   130
        private void SetAssociatedMailItem()
Dean@170
   131
        {
Dean@170
   132
            bool errorOccurred = false;
Dean@170
   133
            Outlook.MailItem omi = null;
Dean@170
   134
Dean@170
   135
            // Null check
Dean@170
   136
            if (!errorOccurred)
Dean@170
   137
            {
Dean@170
   138
                try
Dean@170
   139
                {
Dean@170
   140
                    if (this.OutlookItem == null)
Dean@170
   141
                    {
Dean@170
   142
                        errorOccurred = true;
Dean@170
   143
                    }
Dean@170
   144
                }
Dean@170
   145
                catch (COMException)
Dean@170
   146
                {
Dean@170
   147
                    errorOccurred = true;
Dean@170
   148
                }
Dean@170
   149
            }
Dean@170
   150
Dean@170
   151
            // Attempt to get and cast the outlook mail item
Dean@170
   152
            if (!errorOccurred)
Dean@170
   153
            {
Dean@170
   154
                try
Dean@170
   155
                {
Dean@170
   156
                    omi = (Outlook.MailItem)this.OutlookItem;
Dean@170
   157
                }
Dean@170
   158
                catch
Dean@170
   159
                {
Dean@170
   160
                    errorOccurred = true;
Dean@170
   161
                }
Dean@170
   162
            }
Dean@170
   163
Dean@170
   164
            // Finally set the associated mail item
Dean@170
   165
            if ((errorOccurred) ||
Dean@170
   166
                (omi == null))
Dean@170
   167
            {
Dean@170
   168
                this.associatedMailItem = null;
Dean@170
   169
            }
Dean@170
   170
            else
Dean@170
   171
            {
Dean@170
   172
                // Check if the associated mail item has already been set
Dean@170
   173
                if (this.associatedMailItem != null)
Dean@170
   174
                {
Dean@170
   175
                    // Only re-set the mail item if the EntryID has changed
Dean@170
   176
                    if (this.associatedMailItem.EntryID != omi.EntryID)
Dean@170
   177
                    {
Dean@170
   178
                        this.associatedMailItem = new CryptableMailItem(omi);
Dean@170
   179
                    }
Dean@170
   180
                }
Dean@170
   181
                else
Dean@170
   182
                {
Dean@170
   183
                    this.associatedMailItem = new CryptableMailItem(omi);
Dean@170
   184
                }
Dean@170
   185
            }
Dean@170
   186
Dean@170
   187
            return;
Dean@170
   188
        }
Dean@170
   189
Dean@179
   190
        /// <summary>
Dean@672
   191
        /// Completes the handshake process when the identity of a partner was previously marked as mistrusted.
Dean@281
   192
        /// </summary>
Dean@646
   193
        /// <param name="myself">The personal identity to complete the handshake with.</param>
Dean@646
   194
        /// <param name="partner">The identity of the partner to complete the handshake with.</param>
Dean@672
   195
        private void DoHandshakeForMistrustedKey(PEPIdentity myself,
Dean@672
   196
                                                 PEPIdentity partner)
Dean@281
   197
        {
Dean@281
   198
            DialogResult result;
Dean@281
   199
Dean@281
   200
            result = MessageBox.Show(this.ParentForm,
Dean@672
   201
                                     pEp.Properties.Resources.Message_WarningMistrustedKey,
Dean@378
   202
                                     pEp.Properties.Resources.Message_TitleConfirmOperation,
Dean@423
   203
                                     MessageBoxButtons.YesNo);
Dean@281
   204
Dean@423
   205
            if (result == DialogResult.Yes)
Dean@281
   206
            {
Dean@646
   207
                this.DoHandshake(myself, partner);
Dean@281
   208
            }
Dean@281
   209
Dean@281
   210
            return;
Dean@281
   211
        }
Dean@281
   212
Dean@281
   213
        /// <summary>
Dean@281
   214
        /// Completes the handshake process where the identity of a partner is confirmed.
Dean@179
   215
        /// </summary>
Dean@646
   216
        /// <param name="myself">The personal identity to complete the handshake with.</param>
Dean@646
   217
        /// <param name="partner">The identity of the partner to complete the handshake with.</param>
Dean@646
   218
        private void DoHandshake(PEPIdentity myself,
Dean@646
   219
                                 PEPIdentity partner)
vb@133
   220
        {
Dean@155
   221
            string ownFpr;
Dean@155
   222
            string partnerFpr;
Dean@363
   223
            string trustwordsShort;
Dean@363
   224
            string trustwordsFull;
Dean@155
   225
            string[] lines;
Dean@179
   226
            DialogResult result;
Dean@155
   227
            FormHandshake handshakeDialog;
Dean@155
   228
            FormHandshake.State state = new FormHandshake.State();
markus@201
   229
Dean@740
   230
            Global.AddToLogVerbose("DoHandshake: Handshake started.");
vb@139
   231
Dean@363
   232
            // Process identities
Dean@646
   233
            if (partner.Username == "")
Dean@363
   234
            {
Dean@646
   235
                partner.Username = partner.Address;
vb@133
   236
            }
Dean@646
   237
            partner.UserID = Globals.ThisAddIn.GetUserID(partner.Address);
Dean@363
   238
Dean@363
   239
            // Calculate and add trustwords
Dean@646
   240
            this.CalcTrustwords(myself, partner, out trustwordsShort, out trustwordsFull);
Dean@646
   241
            state.Myself = myself.Copy();
Dean@646
   242
            state.Partner = partner.Copy();
Dean@363
   243
            state.TrustwordsShort = trustwordsShort;
Dean@363
   244
            state.TrustwordsFull = trustwordsFull;
Dean@363
   245
Dean@363
   246
            // Calculate and add fingerprint
Dean@646
   247
            ownFpr = this.ToQuadruple(myself.Fingerprint);
Dean@646
   248
            partnerFpr = this.ToQuadruple(partner.Fingerprint);
vb@133
   249
Dean@646
   250
            if (myself.Fingerprint.CompareTo(partner.Fingerprint) > 0)
vb@133
   251
            {
Dean@155
   252
                lines = new string[3];
Dean@378
   253
                lines[0] = pEp.Properties.Resources.PrivacyStatus_TrustwordsPartnerShortPartner + partnerFpr;
Dean@378
   254
                lines[2] = pEp.Properties.Resources.PrivacyStatus_TrustwordsPartnerShortMyself + ownFpr;
Dean@155
   255
                state.Fingerprint = lines;
vb@133
   256
            }
vb@133
   257
            else
vb@133
   258
            {
Dean@155
   259
                lines = new string[3];
Dean@378
   260
                lines[0] = pEp.Properties.Resources.PrivacyStatus_TrustwordsOwnShortMyself + ownFpr;
Dean@378
   261
                lines[2] = pEp.Properties.Resources.PrivacyStatus_TrustwordsOwnShortPartner + partnerFpr;
Dean@155
   262
                state.Fingerprint = lines;
vb@133
   263
            }
vb@133
   264
Dean@155
   265
            // Create and show handshake dialog
Dean@155
   266
            handshakeDialog = new FormHandshake(state);
Dean@179
   267
            handshakeDialog.StartPosition = FormStartPosition.CenterScreen;
Dean@179
   268
            result = handshakeDialog.ShowDialog(this);
Dean@155
   269
Dean@646
   270
            this.ProcessDoHandshakeResult(result, partner);
Dean@356
   271
Dean@356
   272
            return;
Dean@356
   273
        }
Dean@356
   274
Dean@356
   275
        /// <summary>
Dean@356
   276
        /// Processes the result of the do handshake dialog after a user makes a selection.
Dean@356
   277
        /// </summary>
Dean@356
   278
        /// <param name="result">The result of the handshake dialog selection.</param>
Dean@356
   279
        /// <param name="partner">The identity of the partner to handshake with.</param>
Dean@356
   280
        private void ProcessDoHandshakeResult(DialogResult result,
Dean@384
   281
                                              PEPIdentity partner)
Dean@356
   282
        {
Dean@384
   283
            pEp_identity_s identityPartner = ThisAddIn.pEp.update_identity(partner.ToCOMType());
vb@133
   284
vb@133
   285
            switch (result)
vb@133
   286
            {
vb@133
   287
                case DialogResult.Yes:
Dean@279
   288
                    {
Dean@672
   289
                        // Check if key was previously mistrusted -- warning to user must be displayed earlier
Dean@672
   290
                        if (identityPartner.comm_type == _pEp_comm_type.pEp_ct_mistrusted)
Dean@281
   291
                        {
Dean@281
   292
                            ThisAddIn.pEp.key_reset_trust(ref identityPartner);
Dean@281
   293
                        }
Dean@281
   294
Dean@279
   295
                        identityPartner = ThisAddIn.pEp.trust_personal_key(ref identityPartner);
Dean@279
   296
Dean@279
   297
                        this.UpdateUIFromMailItem();
Dean@279
   298
Dean@279
   299
                        // Update the manager form state
Dean@279
   300
                        if (this.managerForm != null)
Dean@279
   301
                        {
Dean@279
   302
                            this.managerForm.CopyStateToUI(this.GetManagerState());
Dean@279
   303
                        }
Dean@279
   304
Dean@279
   305
                        break;
Dean@279
   306
                    }
vb@133
   307
                case DialogResult.No:
Dean@279
   308
                    {
Dean@279
   309
                        ThisAddIn.pEp.key_compromized(ref identityPartner);
Dean@279
   310
Dean@279
   311
                        this.UpdateUIFromMailItem();
Dean@279
   312
Dean@279
   313
                        // Update the manager form state
Dean@279
   314
                        if (this.managerForm != null)
Dean@279
   315
                        {
Dean@279
   316
                            this.managerForm.CopyStateToUI(this.GetManagerState());
Dean@279
   317
                        }
Dean@279
   318
Dean@279
   319
                        break;
Dean@279
   320
                    }
vb@133
   321
            }
Dean@279
   322
Dean@740
   323
            Global.AddToLogVerbose("ProcessDoHandshakeResult: Handshake complete.");
Dean@740
   324
Dean@279
   325
            return;
vb@133
   326
        }
vb@133
   327
Dean@179
   328
        /// <summary>
Dean@179
   329
        /// Reverses any past handshake confirmation by unconfirming the given identity partner.
Dean@179
   330
        /// </summary>
Dean@384
   331
        /// <param name="partner">The identity of the partner to unconfirm.</param>
Dean@384
   332
        private void UndoHandshake(PEPIdentity partner)
vb@133
   333
        {
Dean@384
   334
            pEp_identity_s identityPartner = ThisAddIn.pEp.update_identity(partner.ToCOMType());
Dean@280
   335
            ThisAddIn.pEp.key_reset_trust(ref identityPartner);
Dean@279
   336
Dean@179
   337
            this.UpdateUIFromMailItem();
Dean@279
   338
Dean@279
   339
            // Update the manager form state
Dean@279
   340
            if (this.managerForm != null)
Dean@279
   341
            {
Dean@279
   342
                this.managerForm.CopyStateToUI(this.GetManagerState());
Dean@279
   343
            }
Dean@279
   344
Dean@279
   345
            return;
vb@133
   346
        }
vb@133
   347
Dean@161
   348
        /// <summary>
Dean@363
   349
        /// Calculates both the short and full trustwords between the given personal identity and the identity partner.
Dean@363
   350
        /// </summary>
Dean@646
   351
        /// <param name="myself">The personal identity.</param>
Dean@646
   352
        /// <param name="partner">The identity of the partner.</param>
Dean@363
   353
        /// <param name="trustwordsShort">The short version of trustwords.</param>
Dean@363
   354
        /// <param name="trustwordsFull">The full/long version of trustwords.</param>
Dean@646
   355
        private void CalcTrustwords(PEPIdentity myself,
Dean@646
   356
                                    PEPIdentity partner,
Dean@363
   357
                                    out string trustwordsShort,
Dean@363
   358
                                    out string trustwordsFull)
Dean@363
   359
        {
Dean@363
   360
            string myShort;
Dean@363
   361
            string myLong;
Dean@363
   362
            string partnerShort;
Dean@363
   363
            string partnerLong;
Dean@363
   364
Dean@674
   365
            myShort = ThisAddIn.pEp.trustwords(myself.Fingerprint, max_words: 5);
Dean@674
   366
            myLong = ThisAddIn.pEp.trustwords(myself.Fingerprint);
Dean@674
   367
            partnerShort = ThisAddIn.pEp.trustwords(partner.Fingerprint, max_words: 5);
Dean@674
   368
            partnerLong = ThisAddIn.pEp.trustwords(partner.Fingerprint);
Dean@363
   369
Dean@646
   370
            if (myself.Fingerprint.CompareTo(partner.Fingerprint) > 0)
Dean@363
   371
            {
Dean@730
   372
                trustwordsShort = partnerShort + Environment.NewLine + myShort;
Dean@730
   373
                trustwordsFull = partnerLong + Environment.NewLine + myLong;
Dean@363
   374
            }
Dean@363
   375
            else
Dean@363
   376
            {
Dean@730
   377
                trustwordsShort = myShort + Environment.NewLine + partnerShort;
Dean@730
   378
                trustwordsFull = myLong + Environment.NewLine + partnerLong;
Dean@363
   379
            }
Dean@363
   380
Dean@363
   381
            return;
Dean@363
   382
        }
Dean@363
   383
Dean@363
   384
        /// <summary>
Dean@161
   385
        /// Formats the given text string as separated 4-character groups.
Dean@161
   386
        /// Example: 49422235FC99585B891C --> 4942 2235 FC99 585B 891C
Dean@161
   387
        /// </summary>
Dean@161
   388
        /// <param name="text">The text to format in 4-character groups.</param>
Dean@161
   389
        /// <returns>The re-formatted string.</returns>
Dean@161
   390
        private string ToQuadruple(string text)
Dean@159
   391
        {
Dean@159
   392
            List<string> result = new List<string>();
Dean@159
   393
Dean@161
   394
            if (text != null)
Dean@159
   395
            {
Dean@161
   396
                for (int i = 0; i < text.Length; i += 4)
Dean@159
   397
                {
Dean@161
   398
                    try
Dean@161
   399
                    {
Dean@161
   400
                        result.Add(text.Substring(i, 4));
Dean@161
   401
                    }
Dean@161
   402
                    catch (ArgumentOutOfRangeException)
Dean@161
   403
                    {
Dean@161
   404
                        result.Add(text.Substring(i));
Dean@161
   405
                        break;
Dean@161
   406
                    }
Dean@159
   407
                }
Dean@159
   408
            }
Dean@159
   409
Dean@159
   410
            return String.Join(" ", result);
Dean@159
   411
        }
markus@201
   412
Dean@196
   413
        /// <summary>
Dean@279
   414
        /// Builds a new manager form state using this encryption state/mail item current state.
Dean@279
   415
        /// </summary>
Dean@279
   416
        /// <returns>A new manager form state.</returns>
Dean@313
   417
        private FormManagePrivacyStatus.State GetManagerState()
Dean@279
   418
        {
Dean@737
   419
            int currIndex = 0;
Dean@527
   420
            bool isMyself;
Dean@664
   421
            bool forceUnencrypted;
Dean@364
   422
            string trustwordsShort;
Dean@364
   423
            string trustwordsFull;
Dean@384
   424
            List<PEPIdentity> identities;
Dean@384
   425
            PEPIdentity myIdentity;
Dean@384
   426
            PEPIdentity incomingIdent;
Dean@259
   427
            _pEp_color identityPartnerColor;
Dean@259
   428
            SelectionItem item;
Dean@312
   429
            PrivacyState state = this.CopyUIToState();
Dean@313
   430
            FormManagePrivacyStatus.State managerState = new FormManagePrivacyStatus.State();
Dean@259
   431
Dean@332
   432
            // Resolve all recipients -- this ensures the identities list is correctly populated
Dean@332
   433
            this.associatedMailItem.ResolveAllRecipients();
Dean@332
   434
Dean@279
   435
            managerState.VisualState = state.Copy();
Dean@279
   436
            managerState.IsIncoming = this.associatedMailItem.IsIncoming;
Dean@259
   437
Dean@653
   438
            if (managerState.IsIncoming)
Dean@259
   439
            {
Dean@384
   440
                identities = new List<PEPIdentity>();
Dean@259
   441
Dean@259
   442
                // Add only one identity
Dean@638
   443
                if (this.associatedMailItem.From != null)
Dean@638
   444
                {
Dean@638
   445
                    incomingIdent = new PEPIdentity();
Dean@638
   446
                    incomingIdent.Address = this.associatedMailItem.From.Address;
Dean@638
   447
                    incomingIdent.Username = this.associatedMailItem.From.Username;
Dean@638
   448
                    incomingIdent.UserID = Globals.ThisAddIn.GetUserID(incomingIdent.Address);
Dean@259
   449
Dean@638
   450
                    identities.Add(incomingIdent);
Dean@638
   451
                }
Dean@259
   452
            }
Dean@259
   453
            else
Dean@259
   454
            {
Dean@395
   455
                identities = this.associatedMailItem.Recipients;
Dean@259
   456
            }
Dean@259
   457
Dean@366
   458
            // Get my identity
Dean@633
   459
            myIdentity = this.associatedMailItem.Myself;
Dean@366
   460
Dean@279
   461
            // Add identities
Dean@394
   462
            identities = PEPIdentity.ToFlatList(identities);
Dean@279
   463
            managerState.Identities.Clear();
Dean@384
   464
            foreach (PEPIdentity ident in identities)
Dean@259
   465
            {
Dean@737
   466
                // Needed so index can be used within anonymous methods without getting into the 'outer variable trap' of currIndex
Dean@737
   467
                int index = currIndex;
Dean@737
   468
Dean@648
   469
                if (ident.IsValid)
Dean@485
   470
                {
Dean@485
   471
                    pEp_identity_s partnerIdentity_s = ThisAddIn.pEp.update_identity(ident.ToCOMType());
Dean@485
   472
                    PEPIdentity partnerIdentity = new PEPIdentity(partnerIdentity_s);
Dean@485
   473
                    identityPartnerColor = ThisAddIn.pEp.identity_color(partnerIdentity_s);
Dean@664
   474
                    forceUnencrypted = Globals.ThisAddIn.ContactIsForceUnencrypted(partnerIdentity.Address);
Dean@259
   475
Dean@527
   476
                    // Check if identity is myself
Dean@713
   477
                    isMyself = PEPIdentity.GetIsMyIdentity(partnerIdentity.Address);
Dean@724
   478
Dean@485
   479
                    item = new SelectionItem();
Dean@485
   480
                    item.TextLine1 = partnerIdentity.Username;
Dean@485
   481
                    item.TextLine2 = partnerIdentity.Address;
Dean@259
   482
Dean@485
   483
                    // Don't show both the user name and address if they are the same
Dean@485
   484
                    if ((item.TextLine1 != null) &&
Dean@485
   485
                        (item.TextLine2 != null) &&
Dean@485
   486
                        (item.TextLine1 == item.TextLine2))
Dean@485
   487
                    {
Dean@485
   488
                        item.IsTwoTextLinesVisible = false;
Dean@485
   489
                    }
Dean@332
   490
Dean@527
   491
                    // Calculate trustwords
Dean@527
   492
                    this.CalcTrustwords(myIdentity,
Dean@527
   493
                                        partnerIdentity,
Dean@527
   494
                                        out trustwordsShort,
Dean@527
   495
                                        out trustwordsFull);
Dean@527
   496
Dean@485
   497
                    // Set image
Dean@664
   498
                    if ((forceUnencrypted) &&
Dean@653
   499
                        (managerState.IsIncoming == false))
Dean@485
   500
                    {
Dean@641
   501
                        // Show the force unencrypted image indicating this is set by the user not the engine
Dean@642
   502
                        item.ItemImage = pEp.Properties.Resources.ImageForceUnencOn;
Dean@641
   503
                    }
Dean@641
   504
                    else
Dean@641
   505
                    {
Dean@641
   506
                        switch (PrivacyState.ConvertRatingToPrivacyColor(identityPartnerColor))
Dean@641
   507
                        {
Dean@641
   508
                            case PrivacyState.PrivacyColor.Green:
Dean@641
   509
                                item.ItemImage = pEp.Properties.Resources.ImagePrivacyStatusGreen;
Dean@641
   510
                                break;
Dean@641
   511
                            case PrivacyState.PrivacyColor.Yellow:
Dean@641
   512
                                item.ItemImage = pEp.Properties.Resources.ImagePrivacyStatusYellow;
Dean@641
   513
                                break;
Dean@641
   514
                            case PrivacyState.PrivacyColor.Red:
Dean@641
   515
                                item.ItemImage = pEp.Properties.Resources.ImagePrivacyStatusRed;
Dean@641
   516
                                break;
Dean@641
   517
                            case PrivacyState.PrivacyColor.NoColor:
Dean@641
   518
                                item.ItemImage = pEp.Properties.Resources.ImagePrivacyStatusNoColor;
Dean@641
   519
                                break;
Dean@641
   520
                            default:
Dean@641
   521
                                item.ItemImage = null;
Dean@641
   522
                                break;
Dean@641
   523
                        }
Dean@485
   524
                    }
Dean@259
   525
Dean@485
   526
                    // Set button
Dean@653
   527
                    if ((isMyself) ||
Dean@664
   528
                        ((forceUnencrypted) &&
Dean@653
   529
                         (managerState.IsIncoming == false)))
Dean@653
   530
                    {
Dean@653
   531
                        item.IsButtonVisible = false;
Dean@653
   532
                        item.IsExpandable = false;
Dean@653
   533
                    }
Dean@653
   534
                    else
Dean@366
   535
                    {
Dean@485
   536
                        if (partnerIdentity.CommunicationType >= _pEp_comm_type.pEp_ct_confirmed_encryption)
Dean@485
   537
                        {
Dean@485
   538
                            // Undo handshake
Dean@485
   539
                            item.TextButton = pEp.Properties.Resources.PrivacyStatus_StopTrusting;
Dean@485
   540
                            item.IsButtonVisible = true;
Dean@646
   541
                            item.ButtonOnClick = (x, y) => { this.UndoHandshake(partnerIdentity.Copy()); };
Dean@356
   542
Dean@485
   543
                            item.IsExpandable = false;
Dean@485
   544
                        }
Dean@485
   545
                        else if (partnerIdentity.CommunicationType >= _pEp_comm_type.pEp_ct_unconfirmed_encryption &&
Dean@485
   546
                                 partnerIdentity.CommunicationType < _pEp_comm_type.pEp_ct_confirmed_encryption)
Dean@485
   547
                        {
Dean@485
   548
                            // Do handshake
Dean@737
   549
                            item.TextButton = pEp.Properties.Resources.PrivacyStatus_Handshake;
Dean@485
   550
                            item.IsButtonVisible = true;
Dean@646
   551
                            item.ButtonOnClick = (x, y) => { this.DoHandshake(myIdentity.Copy(), partnerIdentity.Copy()); };
Dean@356
   552
Dean@485
   553
                            item.IsExpandable = true;
Dean@485
   554
                            item.ExpandedText = Properties.Resources.PrivacyStatus_TrustwordDesc + "\n\n" +
Dean@485
   555
                                                trustwordsShort;
Dean@447
   556
Dean@485
   557
                            item.ExpandedButton1Text = Properties.Resources.PrivacyStatus_SelectTrust;
Dean@646
   558
                            item.ExpandedButton1OnClick = (x, y) => { this.ProcessDoHandshakeResult(DialogResult.Yes, partnerIdentity.Copy()); };
Dean@485
   559
                            item.ExpandedButton1BackColor = PrivacyState.COLOR_GREEN;
Dean@485
   560
                            item.ExpandedButton1ForeColor = Color.White;
Dean@447
   561
Dean@737
   562
                            item.ExpandedButton2Text = Properties.Resources.PrivacyStatus_SelectCancel;
Dean@737
   563
                            item.ExpandedButton2OnClick = (x, y) =>
Dean@737
   564
                                {
Dean@737
   565
                                    FormManagePrivacyStatus.State activeManagerState;
Dean@737
   566
Dean@737
   567
                                    if (this.managerForm != null)
Dean@737
   568
                                    {
Dean@737
   569
                                        activeManagerState = this.managerForm.CopyUIToState();
Dean@737
   570
                
Dean@737
   571
                                        if ((index >= 0) &&
Dean@737
   572
                                            (index < activeManagerState.Identities.Count))
Dean@737
   573
                                        {
Dean@737
   574
                                            item = activeManagerState.Identities[index];
Dean@737
   575
                                            item.TextButton   = pEp.Properties.Resources.PrivacyStatus_Handshake;
Dean@737
   576
                                            item.IsExpanded   = false;
Dean@737
   577
                                            item.IsExpandable = false;
Dean@737
   578
                                        }
Dean@737
   579
                                    }
Dean@737
   580
                                };
Dean@737
   581
Dean@737
   582
                            item.ExpandedButton3Text = Properties.Resources.PrivacyStatus_SelectMistrust;
Dean@737
   583
                            item.ExpandedButton3OnClick = (x, y) => { this.ProcessDoHandshakeResult(DialogResult.No, partnerIdentity.Copy()); };
Dean@737
   584
                            item.ExpandedButton3BackColor = PrivacyState.COLOR_RED;
Dean@737
   585
                            item.ExpandedButton3ForeColor = Color.White;
Dean@485
   586
                        }
Dean@672
   587
                        else if (partnerIdentity.CommunicationType == _pEp_comm_type.pEp_ct_mistrusted)
Dean@485
   588
                        {
Dean@485
   589
                            // Redo handshake with confirmation
Dean@485
   590
                            item.TextButton = pEp.Properties.Resources.PrivacyStatus_Handshake;
Dean@485
   591
                            item.IsButtonVisible = true;
Dean@672
   592
                            item.ButtonOnClick = (x, y) => { this.DoHandshakeForMistrustedKey(myIdentity.Copy(), partnerIdentity.Copy()); };
Dean@641
   593
Dean@641
   594
                            item.IsExpandable = false;
Dean@485
   595
                        }
Dean@485
   596
                        else
Dean@485
   597
                        {
Dean@485
   598
                            item.IsButtonVisible = false;
Dean@641
   599
                            item.IsExpandable = false;
Dean@485
   600
                        }
Dean@366
   601
                    }
Dean@281
   602
                }
Dean@485
   603
                else // Invalid identity
Dean@259
   604
                {
Dean@485
   605
                    item = new SelectionItem();
Dean@485
   606
                    item.TextLine1 = ident.Username;
Dean@485
   607
                    item.TextLine2 = ident.Address;
Dean@485
   608
                    item.ItemImage = null;
Dean@485
   609
                    item.IsTwoTextLinesVisible = true;
Dean@259
   610
                    item.IsButtonVisible = false;
Dean@259
   611
                }
Dean@259
   612
Dean@279
   613
                managerState.Identities.Add(item);
Dean@737
   614
                currIndex++;
Dean@259
   615
            }
Dean@259
   616
Dean@737
   617
            // Attempt to select and expand the first identity requiring a handshake
Dean@375
   618
            for (int i = 0; i < managerState.Identities.Count; i++)
Dean@375
   619
            {
Dean@737
   620
                // Determine if it's a handshake identity by checking if it's expandable
Dean@375
   621
                if (managerState.Identities[i].IsExpandable)
Dean@375
   622
                {
Dean@737
   623
                    managerState.Identities[i].TextButton = Properties.Resources.PrivacyStatus_HandshakeAdvanced;
Dean@737
   624
                    managerState.Identities[i].IsExpanded = true;
Dean@375
   625
                    managerState.SelectedIdentityIndex = i;
Dean@375
   626
                    break;
Dean@375
   627
                }
Dean@375
   628
            }
Dean@375
   629
Dean@279
   630
            return (managerState);
Dean@279
   631
        }
Dean@279
   632
Dean@279
   633
        /// <summary>
Dean@279
   634
        /// Builds the latest state of the encryption status manager then shows the UI.
Dean@279
   635
        /// </summary>
Dean@279
   636
        private void BuildAndShowManager()
Dean@279
   637
        {
Dean@279
   638
            DialogResult result;
Dean@313
   639
            FormManagePrivacyStatus form;
Dean@313
   640
            FormManagePrivacyStatus.State stateOut;
Dean@279
   641
Dean@483
   642
            try
Dean@483
   643
            {
Dean@483
   644
                // Show the form
Dean@483
   645
                form = new FormManagePrivacyStatus();
Dean@483
   646
                form.StartPosition = FormStartPosition.CenterScreen;
Dean@259
   647
Dean@483
   648
                this.managerForm = form;
Dean@483
   649
                result = form.ShowDialog(this.ParentForm, this.GetManagerState(), out stateOut); // Must show as dialog to block code
Dean@483
   650
            }
Dean@483
   651
            catch (Exception ex)
Dean@483
   652
            {
Dean@660
   653
                Global.StopAndSendCrashReport(ex);
Dean@483
   654
            }
Dean@259
   655
Dean@259
   656
            return;
Dean@259
   657
        }
Dean@259
   658
Dean@259
   659
        /// <summary>
Dean@179
   660
        /// Updates the status of the UI state based on the associated mail item.
Dean@179
   661
        /// </summary>
Dean@622
   662
        public void UpdateUIFromMailItem()
Dean@159
   663
        {
Dean@312
   664
            PrivacyState state;
Dean@664
   665
            bool? forceUnencryptedProperty;
Dean@159
   666
Dean@740
   667
            Global.AddToLogVerbose("UpdateUIFromMailItem: Started.");
Dean@740
   668
Dean@173
   669
            if (this.associatedMailItem != null)
Dean@159
   670
            {
Dean@664
   671
                forceUnencryptedProperty = this.associatedMailItem.ForceUnencrypted;
Dean@342
   672
Dean@664
   673
                if ((forceUnencryptedProperty != null) &&
Dean@664
   674
                    ((bool)forceUnencryptedProperty == true))
Dean@159
   675
                {
Dean@342
   676
                    // Force unencrypted
Dean@312
   677
                    state = new PrivacyState(_pEp_color.pEp_rating_unencrypted);
Dean@680
   678
                    this.CopyStateToUI(state);
Dean@740
   679
Dean@740
   680
                    Global.AddToLogVerbose("UpdateUIFromMailItem: Force unencrypted detected.");
Dean@159
   681
                }
Dean@159
   682
                else
Dean@159
   683
                {
Dean@740
   684
                    Global.AddToLogVerbose("UpdateUIFromMailItem: Starting decryption.");
Dean@740
   685
Dean@680
   686
                    // Start the color rating calculation/decryption process
Dean@680
   687
                    this.associatedMailItem.StartDecryption();
Dean@159
   688
                }
Dean@159
   689
            }
Dean@159
   690
Dean@179
   691
            return;
Dean@159
   692
        }
Dean@159
   693
Dean@709
   694
        /// <summary>
Dean@709
   695
        /// Clears the associated unencrypted preview and displays the given note (if any).
Dean@709
   696
        /// </summary>
Dean@709
   697
        /// <param name="note">The note to diplsay.</param>
Dean@709
   698
        private void ClearPreview(string note = null)
Dean@709
   699
        {
Dean@709
   700
            WindowFormRegionCollection formRegions = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveExplorer()];
Dean@709
   701
Dean@709
   702
            if ((formRegions != null) &&
Dean@709
   703
                (formRegions.FormRegionPreviewUnencrypted != null) &&
Dean@709
   704
                (formRegions.FormRegionPreviewUnencrypted.Visible))
Dean@709
   705
            {
Dean@709
   706
                formRegions.FormRegionPreviewUnencrypted.ClearMessage();
Dean@709
   707
                formRegions.FormRegionPreviewUnencrypted.SetNote(note);
Dean@709
   708
            }
Dean@709
   709
Dean@709
   710
            return;
Dean@709
   711
        }
Dean@709
   712
Dean@172
   713
        #region StateMethods
Dean@172
   714
Dean@172
   715
        /// <summary>
Dean@172
   716
        /// Connects or disconnects all control events from the UI.
Dean@172
   717
        /// </summary>
Dean@172
   718
        /// <param name="connect">True to connect events, false to disconnect.</param>
Dean@172
   719
        private void ConnectEvents(bool connect)
Dean@172
   720
        {
Dean@172
   721
            // Connect events only if not already connected
markus@201
   722
            if ((connect == true) &&
Dean@172
   723
                (this.eventsAreConnected == false))
Dean@172
   724
            {
Dean@312
   725
                this.ButtonPrivacyStatus.Click += this.ButtonPrivacyStatus_Click;
Dean@312
   726
                this.ButtonPrivacyStatus.MouseUp += this.ButtonPrivacyStatus_MouseUp;
Dean@179
   727
Dean@172
   728
                this.eventsAreConnected = true;
Dean@172
   729
            }
Dean@172
   730
            // Always attempt to disconnect
Dean@172
   731
            else if (connect == false)
Dean@172
   732
            {
Dean@312
   733
                this.ButtonPrivacyStatus.Click -= this.ButtonPrivacyStatus_Click;
Dean@312
   734
                this.ButtonPrivacyStatus.MouseUp -= this.ButtonPrivacyStatus_MouseUp;
Dean@179
   735
Dean@172
   736
                this.eventsAreConnected = false;
Dean@172
   737
            }
Dean@172
   738
Dean@172
   739
            return;
Dean@172
   740
        }
Dean@172
   741
Dean@172
   742
        /// <summary>
Dean@172
   743
        /// Copies the given state to the UI.
Dean@172
   744
        /// Events are turned off until the process is complete.
Dean@172
   745
        /// </summary>
Dean@172
   746
        /// <param name="state">The state to set to the UI.</param>
Dean@312
   747
        private void CopyStateToUI(PrivacyState state)
Dean@172
   748
        {
Dean@172
   749
            this.ConnectEvents(false);
markus@201
   750
Dean@172
   751
            ///////////////////////////////////////////////////////////
Dean@172
   752
            // Set UI data
Dean@172
   753
            ///////////////////////////////////////////////////////////
Dean@172
   754
Dean@179
   755
            // Save UI state maintained outside of controls
Dean@312
   756
            this.stateUIColorRating = state.PrivacyStatus;
Dean@179
   757
Dean@312
   758
            this.ButtonPrivacyStatus.BackColor = state.BackgroundColor;
Dean@312
   759
            this.ButtonPrivacyStatus.ForeColor = state.ForegroundColor;
Dean@312
   760
            this.ButtonPrivacyStatus.Text = state.ShortText;
Dean@172
   761
Dean@670
   762
            // Update the manager form state
Dean@670
   763
            if (this.managerForm != null)
Dean@670
   764
            {
Dean@670
   765
                this.managerForm.CopyStateToUI(this.GetManagerState());
Dean@670
   766
            }
Dean@670
   767
Dean@172
   768
            this.ConnectEvents(true);
Dean@172
   769
Dean@172
   770
            return;
Dean@172
   771
        }
Dean@172
   772
Dean@172
   773
        /// <summary>
Dean@172
   774
        /// Copies the UI to a new state.
Dean@172
   775
        /// </summary>
Dean@172
   776
        /// <returns>The state of the UI.</returns>
Dean@312
   777
        private PrivacyState CopyUIToState()
Dean@172
   778
        {
Dean@312
   779
            return (new PrivacyState(this.stateUIColorRating));
Dean@172
   780
        }
Dean@172
   781
Dean@172
   782
        #endregion
Dean@172
   783
Dean@159
   784
        /**************************************************************
Dean@159
   785
         * 
Dean@159
   786
         * Event Handling
Dean@159
   787
         * 
Dean@159
   788
         *************************************************************/
Dean@159
   789
Dean@159
   790
        /// <summary>
Dean@680
   791
        /// Event handler that is called when the form region is displayed.
Dean@680
   792
        /// This is called each time the form region looses then regains visiblity 
Dean@680
   793
        /// (for example an other email is selected then back to this one).
Dean@159
   794
        /// </summary>
Dean@312
   795
        private void FormRegionPrivacyStatus_FormRegionShowing(object sender, System.EventArgs e)
Dean@159
   796
        {
Dean@680
   797
            // Do not allow initialization more than once
Dean@680
   798
            if (initialized == false)
Dean@680
   799
            {
Dean@680
   800
                this.SetAssociatedMailItem();
Dean@173
   801
Dean@680
   802
                // Set background color for Office 2013
Dean@159
   803
                try
Dean@159
   804
                {
Dean@680
   805
                    if (Globals.ThisAddIn.Application.Version.Substring(0, 2) == "15")
Dean@159
   806
                    {
Dean@680
   807
                        if (this.IsWithinInspector())
Dean@680
   808
                        {
Dean@680
   809
                            this.BackColor = SystemColors.ButtonFace;
Dean@680
   810
                        }
Dean@680
   811
                        else
Dean@680
   812
                        {
Dean@680
   813
                            this.BackColor = SystemColors.Window;
Dean@680
   814
                        }
Dean@159
   815
                    }
Dean@159
   816
                }
Dean@159
   817
                catch { }
Dean@680
   818
Dean@680
   819
                // Connect cryptable mail item events
Dean@680
   820
                if (this.associatedMailItem != null)
Dean@680
   821
                {
Dean@680
   822
                    try
Dean@680
   823
                    {
Dean@680
   824
                        this.associatedMailItem.PropertyChanged += MailItem_PropertyChanged;
Dean@680
   825
                        this.associatedMailItem.DecryptionComplete += MailItem_DecryptionComplete;
Dean@709
   826
                        this.associatedMailItem.GetMirrorComplete += MailItem_GetMirrorComplete;
Dean@682
   827
                        this.associatedMailItem.Send += MailItem_Send;
Dean@680
   828
Dean@680
   829
                        if (this.associatedMailItem.IsInEncryptedStore &&
Dean@680
   830
                            this.associatedMailItem.IsPGPEncrypted)
Dean@680
   831
                        {
Dean@680
   832
                            this.associatedMailItem.Open += MailItem_Open;
Dean@680
   833
                        }
Dean@680
   834
                    }
Dean@680
   835
                    catch { }
Dean@680
   836
                }
Dean@680
   837
Dean@680
   838
                this.CopyStateToUI(new PrivacyState());
Dean@683
   839
                this.TimerRefresh.Tick += TimerRefresh_Tick;
Dean@680
   840
                this.initialized = true;
Dean@179
   841
            }
Dean@159
   842
Dean@683
   843
            // Call the timer tick method manually to refresh data with no delay
Dean@199
   844
            this.TimerRefresh_Tick(null, new EventArgs());
Dean@179
   845
Dean@179
   846
            return;
Dean@159
   847
        }
Dean@159
   848
Dean@159
   849
        /// <summary>
Dean@159
   850
        /// Event handler for when the form region is closed.
Dean@159
   851
        /// </summary>
Dean@312
   852
        private void FormRegionPrivacyStatus_FormRegionClosed(object sender, System.EventArgs e)
Dean@159
   853
        {
Dean@199
   854
            // Disconnect cryptable mail item events
Dean@190
   855
            if (this.associatedMailItem != null)
Dean@179
   856
            {
Dean@179
   857
                try
Dean@179
   858
                {
Dean@445
   859
                    this.associatedMailItem.PropertyChanged -= MailItem_PropertyChanged;
Dean@680
   860
                    this.associatedMailItem.DecryptionComplete -= MailItem_DecryptionComplete;
Dean@709
   861
                    this.associatedMailItem.GetMirrorComplete -= MailItem_GetMirrorComplete;
markus@201
   862
                    this.associatedMailItem.Open -= MailItem_Open;
Dean@682
   863
                    this.associatedMailItem.Send -= MailItem_Send;
Dean@179
   864
                }
Dean@179
   865
                catch { }
Dean@179
   866
            }
Dean@179
   867
Dean@682
   868
            // Stop and disconnect the refresh timer
Dean@682
   869
            this.TimerRefresh.Stop();
Dean@682
   870
            this.TimerRefresh.Enabled = false;
Dean@682
   871
            this.TimerRefresh.Tick -= TimerRefresh_Tick;
Dean@682
   872
Dean@179
   873
            return;
Dean@179
   874
        }
Dean@179
   875
Dean@179
   876
        /// <summary>
Dean@179
   877
        /// Event handler called after the refresh timer has elapsed.
Dean@179
   878
        /// </summary>
Dean@179
   879
        private void TimerRefresh_Tick(object sender, EventArgs e)
Dean@179
   880
        {
Dean@199
   881
            bool tryAgain = false;
Dean@684
   882
            bool markForDownload = false;
Dean@179
   883
            this.TimerRefresh.Enabled = false; // Only once
Dean@684
   884
            Outlook.OlDownloadState dlState;
markus@201
   885
Dean@709
   886
            /* The Refresh/UI_Update process is a little more complicated here than other forms.
Dean@709
   887
             * There are the following components:
Dean@709
   888
             *   1. TimerRefresh_Tick
Dean@709
   889
             *        This is the main timer tick event handler called any time
Dean@709
   890
             *        a refresh was requested and hasn't been run yet. A refresh
Dean@709
   891
             *        is requested either at initialization or when a property changes
Dean@709
   892
             *        (such as MailItem_PropertyChanged). It is on a timer as many 
Dean@709
   893
             *        property change events could occur rapidy, but only one refresh should
Dean@709
   894
             *        occur for performance reasons.
Dean@709
   895
             * 
Dean@709
   896
             *   2. UpdateUIFromMailItem
Dean@709
   897
             *        This will re-calculate the mail item's color rating and then update the UI.
Dean@709
   898
             *        However, if a mail item is not forcefully unencrypted, it will just call StartDecryption.
Dean@709
   899
             * 
Dean@709
   900
             *   3. MailItem_DecryptionComplete
Dean@709
   901
             *        When decryption of the mail item is complete, this even handler will be called.
Dean@709
   902
             *        This will update the UI with the latest color rating then call StartGetMirror.
Dean@709
   903
             *        The CopyStateToUI method is used which means any open privacy status form will also
Dean@709
   904
             *        be updated.
Dean@709
   905
             * 
Dean@709
   906
             *   4. MailItem_GetMirrorComplete
Dean@709
   907
             *        This is the final step in updating the UI, after a mirror is located, it's contents
Dean@709
   908
             *        will be shown to the unencrypted preview.
Dean@709
   909
             * 
Dean@709
   910
             * The general calling sequence is as shown above 1->4 with each component calling the next.
Dean@709
   911
             * However, for methods that update the mail item directly, commonly only 2->4 is needed.
Dean@709
   912
             */
Dean@709
   913
Dean@179
   914
            // Ensure the tick method is not called more than once
Dean@179
   915
            if (refreshOngoing == false)
Dean@179
   916
            {
Dean@179
   917
                this.refreshOngoing = true;
Dean@179
   918
Dean@179
   919
                if (this.associatedMailItem != null)
Dean@179
   920
                {
Dean@684
   921
                    // Attempt to get the download state
Dean@684
   922
                    try
Dean@684
   923
                    {
Dean@684
   924
                        dlState = this.associatedMailItem.DownloadState;
Dean@684
   925
                    }
Dean@684
   926
                    catch (Exception ex)
Dean@684
   927
                    {
Dean@684
   928
                        Global.AddToLog("TimerRefresh_Tick: Get DownloadState failed, " + ex.ToString());
Dean@684
   929
Dean@684
   930
                        // Assume everything is downloaded, but try to download again as well
Dean@684
   931
                        dlState = Outlook.OlDownloadState.olFullItem;
Dean@684
   932
                        markForDownload = true;
Dean@684
   933
                    }
Dean@684
   934
Dean@684
   935
                    if (dlState == Outlook.OlDownloadState.olFullItem)
Dean@179
   936
                    {
Dean@709
   937
                        // Clear any existing preview and update
Dean@709
   938
                        this.ClearPreview(Properties.Resources.Message_Opening);
Dean@179
   939
                        this.UpdateUIFromMailItem();
Dean@179
   940
                    }
Dean@179
   941
                    else
Dean@179
   942
                    {
Dean@684
   943
                        markForDownload = true;
Dean@684
   944
                    }
Dean@684
   945
Dean@684
   946
                    if (markForDownload)
Dean@684
   947
                    {
Dean@684
   948
                        // Try to mark the message for full download
Dean@684
   949
                        try
Dean@684
   950
                        {
Dean@684
   951
                            this.associatedMailItem.MarkForDownload = Outlook.OlRemoteStatus.olMarkedForDownload;
Dean@684
   952
                            tryAgain = true;
Dean@684
   953
                        }
Dean@684
   954
                        catch (Exception ex)
Dean@684
   955
                        {
Dean@684
   956
                            Global.AddToLog("TimerRefresh_Tick: MarkForDownload failed, " + ex.ToString());
Dean@684
   957
                        }
Dean@179
   958
                    }
Dean@179
   959
                }
Dean@179
   960
Dean@199
   961
                // Set the timer to refresh again later automatically
Dean@199
   962
                if (tryAgain)
Dean@199
   963
                {
Dean@199
   964
                    this.TimerRefresh.Interval = 100;
Dean@199
   965
                    this.TimerRefresh.Enabled = true;
Dean@199
   966
                }
Dean@199
   967
Dean@179
   968
                this.refreshOngoing = false;
Dean@179
   969
            }
Dean@175
   970
Dean@159
   971
            return;
Dean@159
   972
        }
Dean@159
   973
Dean@169
   974
        /// <summary>
Dean@680
   975
        /// Event handler for when the decryption process is completed in the associated mail item.
Dean@709
   976
        /// This will then update the form region UI and the privacy status window as needed.
Dean@680
   977
        /// </summary>
Dean@704
   978
        private void MailItem_DecryptionComplete(object sender, CryptableMailItem.DecryptionEventArgs e)
Dean@680
   979
        {
Dean@740
   980
            Global.AddToLogVerbose("MailItem_DecryptionComplete: Decryption completed.");
Dean@740
   981
Dean@680
   982
            try
Dean@680
   983
            {
Dean@680
   984
                // Marshal code back to UI thread as necessary
Dean@680
   985
                this.Invoke(new Action(() =>
Dean@680
   986
                    {
Dean@680
   987
                        this.CopyStateToUI(new PrivacyState(e.ColorRating));
Dean@709
   988
Dean@709
   989
                        /* Create the unencrypted preview if the mail item is encrypted and
Dean@709
   990
                         * it is in an encrypted (untrusted) store
Dean@709
   991
                         * 
Dean@709
   992
                         * This is done here because FormRegionPrivacyStatus has the cryptable mail item and
Dean@709
   993
                         * it also is initialized after FormRegionPreviewUnencrypted.
Dean@709
   994
                         */
Dean@747
   995
                        try
Dean@709
   996
                        {
Dean@747
   997
                            if (this.associatedMailItem.IsInEncryptedStore &&
Dean@747
   998
                                this.associatedMailItem.IsPGPEncrypted)
Dean@747
   999
                            {
Dean@747
  1000
                                Global.AddToLogVerbose("MailItem_DecryptionComplete: Starting mirror location.");
Dean@747
  1001
                                this.associatedMailItem.StartGetMirror();
Dean@747
  1002
                            }
Dean@747
  1003
                            else
Dean@747
  1004
                            {
Dean@747
  1005
                                this.ClearPreview();
Dean@747
  1006
                            }
Dean@709
  1007
                        }
Dean@747
  1008
                        catch (Exception ex)
Dean@719
  1009
                        {
Dean@747
  1010
                            // Error is possible in some situations where the mail item was deleted or moved while decryption was ongoing.
Dean@747
  1011
                            // While rare, just log the issue and stop the process
Dean@747
  1012
                            Global.AddToLog("MailItem_DecryptionComplete: Failed to start mirror location, " + ex.ToString());
Dean@719
  1013
                        }
Dean@680
  1014
                    }));
Dean@680
  1015
            }
Dean@680
  1016
            catch (Exception ex)
Dean@680
  1017
            {
Dean@680
  1018
                Global.AddToLog("MailItem_DecryptionComplete: Error setting UI state, " + ex.ToString());
Dean@680
  1019
            }
Dean@680
  1020
Dean@680
  1021
            return;
Dean@680
  1022
        }
Dean@680
  1023
Dean@680
  1024
        /// <summary>
Dean@709
  1025
        /// Event handler for when the get mirror locating process is complete for the associated mail item.
Dean@709
  1026
        /// This will then update the unencrypted preview in the UI.
Dean@709
  1027
        /// </summary>
Dean@709
  1028
        private void MailItem_GetMirrorComplete(object sender, CryptableMailItem.GetMirrorEventArgs e)
Dean@709
  1029
        {
Dean@709
  1030
            try
Dean@709
  1031
            {
Dean@709
  1032
                // Marshal code back to UI thread as necessary
Dean@709
  1033
                this.Invoke(new Action(() =>
Dean@709
  1034
                    {
Dean@709
  1035
                        WindowFormRegionCollection formRegions = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveExplorer()];
Dean@709
  1036
Dean@709
  1037
                        if ((formRegions != null) &&
Dean@709
  1038
                            (formRegions.FormRegionPreviewUnencrypted != null) &&
Dean@709
  1039
                            (formRegions.FormRegionPreviewUnencrypted.Visible))
Dean@709
  1040
                        {
Dean@709
  1041
                            formRegions.FormRegionPreviewUnencrypted.SetMessage(e.Mirror);
Dean@740
  1042
                            Global.AddToLogVerbose("MailItem_GetMirrorComplete: Mirror found and displayed.");
Dean@709
  1043
                        }
Dean@709
  1044
                    }));
Dean@709
  1045
            }
Dean@709
  1046
            catch (Exception ex)
Dean@709
  1047
            {
Dean@709
  1048
                Global.AddToLog("MailItem_GetMirrorComplete: Error displaying preview, " + ex.ToString());
Dean@709
  1049
            }
Dean@709
  1050
Dean@709
  1051
            return;
Dean@709
  1052
        }
Dean@709
  1053
Dean@709
  1054
        /// <summary>
Dean@169
  1055
        /// Event handler for when a mail item is being opened in an inspector.
Dean@180
  1056
        /// See: https://msdn.microsoft.com/en-us/library/office/ff865989.aspx
Dean@169
  1057
        /// </summary>
Dean@169
  1058
        /// <param name="cancel">Whether to cancel the event: Value is False when the event occurs. 
Dean@169
  1059
        /// If the event procedure sets this argument to True, the open operation is not completed 
Dean@169
  1060
        /// and the inspector is not displayed.</param>
Dean@169
  1061
        private void MailItem_Open(ref bool cancel)
Dean@159
  1062
        {
Dean@720
  1063
            if (this.associatedMailItem != null && this.associatedMailItem.DisplayMirror())
Dean@169
  1064
            {
Dean@169
  1065
                cancel = true;
Dean@169
  1066
            }
Dean@169
  1067
Dean@169
  1068
            return;
Dean@159
  1069
        }
Dean@159
  1070
Dean@169
  1071
        /// <summary>
Dean@682
  1072
        /// Event handler for when a mail item is sent.
Dean@682
  1073
        /// See: https://msdn.microsoft.com/en-us/library/office/ff865379.aspx
Dean@682
  1074
        /// </summary>
Dean@682
  1075
        /// <param name="cancel">Whether to cancel the event: Value is False when the event occurs. 
Dean@682
  1076
        /// If the event procedure sets this argument to True, the send operation is not completed 
Dean@682
  1077
        /// and the inspector is left open.</param>
Dean@682
  1078
        private void MailItem_Send(ref bool cancel)
Dean@682
  1079
        {
Dean@682
  1080
            // Stop and disconnect the refresh timer
Dean@682
  1081
            // This is necessary so an ongoing refresh doesn't try to access a mail item as it's being moved
Dean@682
  1082
            this.TimerRefresh.Stop();
Dean@682
  1083
            this.TimerRefresh.Enabled = false;
Dean@682
  1084
            this.TimerRefresh.Tick -= TimerRefresh_Tick;
Dean@682
  1085
Dean@682
  1086
            return;
Dean@682
  1087
        }
Dean@682
  1088
Dean@682
  1089
        /// <summary>
Dean@169
  1090
        /// Event handler for when a mail item property is changed.
Dean@169
  1091
        /// See: https://msdn.microsoft.com/en-us/library/office/ff866739.aspx
Dean@169
  1092
        /// </summary>
Dean@169
  1093
        /// <param name="propertyName">The name of the property that was changed.</param>
Dean@445
  1094
        private void MailItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
Dean@159
  1095
        {
Dean@445
  1096
            switch (e.PropertyName.ToUpper())
Dean@159
  1097
            {
Dean@179
  1098
                case "TO":
Dean@179
  1099
                    // Start the refresh timer
Dean@179
  1100
                    this.TimerRefresh.Enabled = true;
Dean@159
  1101
                    break;
Dean@159
  1102
                // Outlook bug: there are always both events, so one is enough
Dean@159
  1103
                //case "CC":
Dean@179
  1104
                //    // Start the refresh timer
Dean@179
  1105
                //    this.TimerRefresh.Enabled = true;
Dean@159
  1106
                //    break;
Dean@159
  1107
            }
Dean@169
  1108
Dean@169
  1109
            return;
Dean@159
  1110
        }
Dean@159
  1111
Dean@179
  1112
        /// <summary>
Dean@312
  1113
        /// Event handler for when the privacy status button is clicked.
Dean@179
  1114
        /// </summary>
Dean@312
  1115
        private void ButtonPrivacyStatus_Click(object sender, EventArgs e)
vb@133
  1116
        {
Dean@310
  1117
            this.BuildAndShowManager();
Dean@179
  1118
            return;
vb@133
  1119
        }
vb@133
  1120
Dean@179
  1121
        /// <summary>
Dean@312
  1122
        /// Event handler for when a mouse button is released over the privacy status button.
Dean@179
  1123
        /// </summary>
Dean@312
  1124
        private void ButtonPrivacyStatus_MouseUp(object sender, MouseEventArgs e)
vb@133
  1125
        {
Dean@179
  1126
            return;
vb@133
  1127
        }
vb@133
  1128
    }
vb@133
  1129
}