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