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