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