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