UI/FormRegionPrivacyStatus.cs
author Dean
Fri, 14 Oct 2016 15:58:36 +0200
changeset 1362 d29258bb3fb7
parent 1353 a72645a42c8d
child 1375 4e230f31c813
permissions -rw-r--r--
Add Rating to PEPIdentity.
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
        {
markus@1337
   272
            pEpRating partnerIdentityRating;
markus@1337
   273
            pEpColor partnerIdentityColor;
markus@1337
   274
            pEpIdentity identityPartner = ThisAddIn.PEPEngine.UpdateIdentity(partner.ToCOMType());
vb@133
   275
vb@133
   276
            switch (result)
vb@133
   277
            {
vb@133
   278
                case DialogResult.Yes:
Dean@279
   279
                    {
Dean@1310
   280
                        // Get the rating/color to determine if key was previously mistrusted -- warning to user must be displayed earlier
Dean@1295
   281
                        try
Dean@281
   282
                        {
markus@1337
   283
                            partnerIdentityRating = ThisAddIn.PEPEngine.IdentityRating(identityPartner);
Dean@1310
   284
                        }
Dean@1310
   285
                        catch (COMException ex)
Dean@1310
   286
                        {
markus@1337
   287
                            partnerIdentityRating = pEpRating.pEpRatingUndefined;
Dean@1310
   288
                            Log.Warning("ProcessDoHandshakeResult: Failed to get identity rating, " + ex.ToString());
Dean@1310
   289
                        }
Dean@1341
   290
                        partnerIdentityColor = partnerIdentityRating.ToColor();
Dean@1310
   291
Dean@1310
   292
                        // Process result
Dean@1310
   293
                        try
Dean@1310
   294
                        {
markus@1337
   295
                            if (partnerIdentityColor == pEpColor.pEpColorRed)
Dean@1295
   296
                            {
markus@1337
   297
                                ThisAddIn.PEPEngine.KeyResetTrust(ref identityPartner);
Dean@1295
   298
                            }
Dean@1295
   299
markus@1337
   300
                            identityPartner = ThisAddIn.PEPEngine.TrustPersonalKey(ref identityPartner);
Dean@281
   301
                        }
Dean@1295
   302
                        catch (Exception ex)
Dean@1295
   303
                        {
Dean@1295
   304
                            Log.Error("ProcessDoHandshakeResult: Error occured while trying to set trust: " + ex.ToString());
Dean@1295
   305
                        }
Dean@279
   306
Dean@1130
   307
                        this.ImmediateRatingAndUIUpdate();
Dean@1117
   308
                        this.UpdateManagePrivacyStatusForm();
Dean@279
   309
Dean@279
   310
                        break;
Dean@279
   311
                    }
vb@133
   312
                case DialogResult.No:
Dean@279
   313
                    {
Dean@1295
   314
                        try
Dean@1295
   315
                        {
markus@1337
   316
                            ThisAddIn.PEPEngine.KeyMistrusted(ref identityPartner);
Dean@1295
   317
                        }
Dean@1295
   318
                        catch (Exception ex)
Dean@1295
   319
                        {
Dean@1295
   320
                            Log.Error("ProcessDoHandshakeResult: Error occured while trying to mistrust key: " + ex.ToString());
Dean@1295
   321
                        }
Dean@279
   322
Dean@1130
   323
                        this.ImmediateRatingAndUIUpdate();
Dean@1117
   324
                        this.UpdateManagePrivacyStatusForm();
Dean@279
   325
Dean@279
   326
                        break;
Dean@279
   327
                    }
vb@133
   328
            }
Dean@279
   329
Dean@1249
   330
            Log.Verbose("ProcessDoHandshakeResult: Handshake complete.");
Dean@740
   331
Dean@279
   332
            return;
vb@133
   333
        }
vb@133
   334
Dean@179
   335
        /// <summary>
Dean@179
   336
        /// Reverses any past handshake confirmation by unconfirming the given identity partner.
Dean@179
   337
        /// </summary>
Dean@384
   338
        /// <param name="partner">The identity of the partner to unconfirm.</param>
Dean@384
   339
        private void UndoHandshake(PEPIdentity partner)
vb@133
   340
        {
markus@1337
   341
            pEpIdentity identityPartner = ThisAddIn.PEPEngine.UpdateIdentity(partner.ToCOMType());
markus@1337
   342
            ThisAddIn.PEPEngine.KeyResetTrust(ref identityPartner);
Dean@279
   343
Dean@1130
   344
            this.ImmediateRatingAndUIUpdate();
Dean@1117
   345
            this.UpdateManagePrivacyStatusForm();
Dean@279
   346
Dean@279
   347
            return;
vb@133
   348
        }
vb@133
   349
Dean@161
   350
        /// <summary>
Dean@279
   351
        /// Builds a new manager form state using this encryption state/mail item current state.
Dean@279
   352
        /// </summary>
Dean@279
   353
        /// <returns>A new manager form state.</returns>
Dean@1069
   354
        private FormControlManagePrivacyStatus.State GetManagerState()
Dean@279
   355
        {
Dean@737
   356
            int currIndex = 0;
Dean@527
   357
            bool isMyself;
Dean@364
   358
            string trustwordsShort;
Dean@364
   359
            string trustwordsFull;
Dean@1069
   360
            BitmapImage imageForceUnencOn;
Dean@1069
   361
            BitmapImage imageGreen;
Dean@1069
   362
            BitmapImage imageNoColor;
Dean@1069
   363
            BitmapImage imageRed;
Dean@1069
   364
            BitmapImage imageYellow;
Dean@384
   365
            List<PEPIdentity> identities;
Dean@1106
   366
            PEPIdentity identity;
Dean@384
   367
            PEPIdentity myIdentity;
Dean@259
   368
            SelectionItem item;
Dean@1069
   369
            FormControlManagePrivacyStatus.State managerState = new FormControlManagePrivacyStatus.State();
Dean@1069
   370
Dean@769
   371
            if (this.associatedMailItem != null)
Dean@769
   372
            {
Dean@1298
   373
                // Load all images from resources
Dean@1298
   374
                imageForceUnencOn = new BitmapImage(new Uri("pack://application:,,,/pEp;component/Resources/ImageForceUnencOn.png", UriKind.RelativeOrAbsolute));
Dean@1298
   375
                imageGreen = new BitmapImage(new Uri("pack://application:,,,/pEp;component/Resources/ImagePrivacyStatusGreen.png", UriKind.RelativeOrAbsolute));
Dean@1298
   376
                imageNoColor = new BitmapImage(new Uri("pack://application:,,,/pEp;component/Resources/ImagePrivacyStatusNoColor.png", UriKind.RelativeOrAbsolute));
Dean@1298
   377
                imageRed = new BitmapImage(new Uri("pack://application:,,,/pEp;component/Resources/ImagePrivacyStatusRed.png", UriKind.RelativeOrAbsolute));
Dean@1298
   378
                imageYellow = new BitmapImage(new Uri("pack://application:,,,/pEp;component/Resources/ImagePrivacyStatusYellow.png", UriKind.RelativeOrAbsolute));
Dean@1298
   379
Dean@1298
   380
                /* Resolve all recipients -- this ensures the identities list is correctly populated
Dean@1298
   381
                 *
Dean@1298
   382
                 * Note: The PropertyChanged changed event must be disconnected before trying to resolve.
Dean@1298
   383
                 * This is because the resolve process can modify the contents of the mail item which triggers an event.
Dean@1298
   384
                 * The PropertyChanged event would then trigger a UI refresh cycle. However, because the GetManagerState itself 
Dean@1298
   385
                 * is called within the UI refresh, an infinite loop could occur trying to resolve a recipient that 
Dean@1298
   386
                 * cannot be resolved (no address).
Dean@1298
   387
                 */
Dean@769
   388
                this.associatedMailItem.PropertyChanged -= MailItem_PropertyChanged;
Dean@769
   389
                this.associatedMailItem.ResolveAllRecipients();
Dean@769
   390
                this.associatedMailItem.PropertyChanged += MailItem_PropertyChanged;
Dean@332
   391
Dean@1298
   392
                managerState.Rating = this.FormControlPrivacyStatusChild.DisplayState.Rating;
Dean@1298
   393
                managerState.IsIncoming = this.associatedMailItem.IsIncoming;
Dean@259
   394
Dean@1298
   395
                // Get identities
Dean@1298
   396
                identities = this.associatedMailItem.Recipients;
Dean@1298
   397
                myIdentity = this.associatedMailItem.Myself;
Dean@1106
   398
Dean@1298
   399
                // Include the from identity for incoming messages at the beginning
Dean@1298
   400
                identity = this.associatedMailItem.From;
Dean@1298
   401
                if ((this.associatedMailItem.IsIncoming) &&
Dean@1298
   402
                    (identity != null))
Dean@1298
   403
                {
Dean@1298
   404
                    identities.Insert(0, identity);
Dean@1298
   405
                }
Dean@259
   406
Dean@1298
   407
                // Remove own identity in the MailItem from the list
Dean@1298
   408
                if (myIdentity != null)
Dean@638
   409
                {
Dean@1298
   410
                    for (int i = (identities.Count - 1); i >= 0; i--)
Dean@1106
   411
                    {
Dean@1298
   412
                        if ((identities[i] != null) &&
Dean@1298
   413
                            (identities[i].EqualsByAddress(myIdentity)))
Dean@1298
   414
                        {
Dean@1298
   415
                            identities.RemoveAt(i);
Dean@1298
   416
                        }
Dean@1106
   417
                    }
Dean@638
   418
                }
Dean@366
   419
Dean@1298
   420
                // Add identities
Dean@1298
   421
                identities = PEPIdentity.ToFlatList(identities);
Dean@1298
   422
                managerState.Identities.Clear();
Dean@1298
   423
                foreach (PEPIdentity ident in identities)
Dean@1298
   424
                {
Dean@1298
   425
                    // Needed so index can be used within anonymous methods without getting into the 'outer variable trap' of currIndex
Dean@1298
   426
                    int index = currIndex;
Dean@737
   427
Dean@1298
   428
                    if (ident.IsAddressValid)
Dean@1298
   429
                    {
Dean@1298
   430
                        // Update the partner identity to get a fingerprint, preserve IsForceUnencrypted
markus@1337
   431
                        pEpIdentity partnerIdentity_s = ThisAddIn.PEPEngine.UpdateIdentity(ident.ToCOMType());
Dean@1298
   432
                        PEPIdentity partnerIdentity = new PEPIdentity(partnerIdentity_s);
Dean@1298
   433
                        partnerIdentity.IsForceUnencrypted = ident.IsForceUnencrypted;
Dean@774
   434
Dean@1298
   435
                        try
Dean@1298
   436
                        {
Dean@1362
   437
                            partnerIdentity.Rating = ThisAddIn.PEPEngine.IdentityRating(partnerIdentity_s);
Dean@1298
   438
                        }
Dean@1298
   439
                        catch (COMException ex)
Dean@1298
   440
                        {
Dean@1362
   441
                            partnerIdentity.Rating = pEpRating.pEpRatingUndefined;
Dean@1298
   442
                            Log.Warning("GetManagerState: Failed to get identity rating, " + ex.ToString());
Dean@1298
   443
                        }
Dean@1018
   444
Dean@1298
   445
                        isMyself = PEPIdentity.GetIsOwnIdentity(partnerIdentity.Address);
Dean@724
   446
Dean@1298
   447
                        // Calculate trustwords
Dean@1298
   448
                        Globals.ThisAddIn.CalcTrustwords(myIdentity,
Dean@1298
   449
                                                         partnerIdentity,
Dean@1298
   450
                                                         out trustwordsShort,
Dean@1298
   451
                                                         out trustwordsFull,
Dean@1298
   452
                                                         Globals.ThisAddIn.Settings.TrustwordsCulture?.TwoLetterISOLanguageName);
Dean@880
   453
Dean@1298
   454
                        item = new SelectionItem();
Dean@1348
   455
                        item.TextLine1 = partnerIdentity.UserName;
Dean@1298
   456
                        item.TextLine2 = partnerIdentity.Address;
Dean@1298
   457
                        item.Tag = (string.IsNullOrWhiteSpace(partnerIdentity.Fingerprint) ? null : trustwordsShort);
Dean@259
   458
Dean@1298
   459
                        // Don't show both the user name and address if they are the same
Dean@1298
   460
                        if ((item.TextLine1 != null) &&
Dean@1298
   461
                            (item.TextLine2 != null) &&
Dean@1298
   462
                            (item.TextLine1 == item.TextLine2))
Dean@1298
   463
                        {
Dean@1298
   464
                            item.IsTwoTextLinesVisible = false;
Dean@1298
   465
                        }
Dean@332
   466
Dean@1298
   467
                        // Set image
Dean@1298
   468
                        if ((partnerIdentity.IsForceUnencryptedBool) &&
Dean@1298
   469
                            (managerState.IsIncoming == false))
Dean@641
   470
                        {
Dean@1298
   471
                            item.ItemImage = imageForceUnencOn;
Dean@641
   472
                        }
Dean@1298
   473
                        else
Dean@1298
   474
                        {
Dean@1362
   475
                            switch (partnerIdentity.Rating.ToColor())
Dean@1298
   476
                            {
markus@1337
   477
                                case pEpColor.pEpColorGreen:
Dean@1298
   478
                                    item.ItemImage = imageGreen;
Dean@1298
   479
                                    break;
markus@1337
   480
                                case pEpColor.pEpColorYellow:
Dean@1298
   481
                                    item.ItemImage = imageYellow;
Dean@1298
   482
                                    break;
markus@1337
   483
                                case pEpColor.pEpColorRed:
Dean@1298
   484
                                    item.ItemImage = imageRed;
Dean@1298
   485
                                    break;
markus@1337
   486
                                case pEpColor.pEpColorNoColor:
Dean@1298
   487
                                    item.ItemImage = imageNoColor;
Dean@1298
   488
                                    break;
Dean@1298
   489
                                default:
Dean@1298
   490
                                    item.ItemImage = null;
Dean@1298
   491
                                    break;
Dean@1298
   492
                            }
Dean@1298
   493
                        }
Dean@259
   494
Dean@1298
   495
                        // Set button
Dean@1298
   496
                        if ((isMyself) ||
Dean@1298
   497
                            ((partnerIdentity.IsForceUnencryptedBool) &&
Dean@1298
   498
                             (managerState.IsIncoming == false)))
Dean@485
   499
                        {
Dean@1298
   500
                            item.IsButtonVisible = false;
Dean@641
   501
                            item.IsExpandable = false;
Dean@485
   502
                        }
Dean@485
   503
                        else
Dean@485
   504
                        {
Dean@1362
   505
                            switch (partnerIdentity.Rating.ToColor())
Dean@1298
   506
                            {
Dean@1362
   507
                                case pEpColor.pEpColorGreen:
Dean@1362
   508
                                    {
Dean@1362
   509
                                        // Undo handshake
Dean@1362
   510
                                        item.TextButton = pEp.Properties.Resources.PrivacyStatus_StopTrusting;
Dean@1362
   511
                                        item.IsButtonVisible = true;
Dean@1362
   512
                                        item.ButtonOnClick = (x, y) => { this.UndoHandshake(partnerIdentity.Copy()); };
Dean@1298
   513
Dean@1362
   514
                                        item.IsExpandable = false;
Dean@1298
   515
Dean@1362
   516
                                        break;
Dean@1362
   517
                                    }
Dean@1362
   518
                                case pEpColor.pEpColorYellow:
Dean@1362
   519
                                    {
Dean@1362
   520
                                        // Do handshake
Dean@1362
   521
                                        item.TextButton = pEp.Properties.Resources.PrivacyStatus_Handshake;
Dean@1362
   522
                                        item.IsButtonVisible = true;
Dean@1362
   523
                                        item.ButtonOnClick = (x, y) => { this.DoHandshake(myIdentity.Copy(), partnerIdentity.Copy()); };
Dean@1298
   524
Dean@1362
   525
                                        item.IsExpandable = true;
Dean@1362
   526
                                        item.ExpandedText = pEp.Properties.Resources.Handshake_ConfirmTrustwordsText + "\n\n" +
Dean@1362
   527
                                                            trustwordsShort;
Dean@1298
   528
Dean@1362
   529
                                        item.ExpandedButton1Text = pEp.Properties.Resources.Handshake_ConfirmText;
Dean@1362
   530
                                        item.ExpandedButton1OnClick = (x, y) => { this.ProcessDoHandshakeResult(DialogResult.Yes, partnerIdentity.Copy()); };
Dean@1362
   531
                                        item.ExpandedButton1Style = (Style)Globals.ResourceDict["StyleConfirmButton"];
Dean@1362
   532
Dean@1362
   533
                                        item.ExpandedButton2Text = pEp.Properties.Resources.Handshake_CancelText;
Dean@1362
   534
                                        item.ExpandedButton2OnClick = (x, y) =>
Dean@1362
   535
                                        {
Dean@1362
   536
                                            SelectionItem selItem;
Dean@1362
   537
                                            FormControlManagePrivacyStatus.State activeState;
Dean@1362
   538
Dean@1362
   539
                                            if (this.managerForm != null)
Dean@1362
   540
                                            {
Dean@1362
   541
                                                activeState = this.managerForm.FormControl.DisplayState;
Dean@1362
   542
Dean@1362
   543
                                                if ((index >= 0) &&
Dean@1362
   544
                                                    (index < activeState.Identities.Count))
Dean@1362
   545
                                                {
Dean@1362
   546
                                                    selItem = activeState.Identities[index];
Dean@1362
   547
                                                    selItem.TextButton = pEp.Properties.Resources.PrivacyStatus_Handshake;
Dean@1362
   548
                                                    selItem.IsExpanded = false;
Dean@1362
   549
                                                    selItem.IsExpandable = false;
Dean@1362
   550
                                                }
Dean@1362
   551
                                            }
Dean@1362
   552
                                        };
Dean@1362
   553
                                        item.ExpandedButton2Style = (Style)Globals.ResourceDict["StyleCancelButton"];
Dean@1362
   554
Dean@1362
   555
                                        item.ExpandedButton3Text = pEp.Properties.Resources.Handshake_WrongText;
Dean@1362
   556
                                        item.ExpandedButton3OnClick = (x, y) => { this.ProcessDoHandshakeResult(DialogResult.No, partnerIdentity.Copy()); };
Dean@1362
   557
                                        item.ExpandedButton3Style = (Style)Globals.ResourceDict["StyleWrongButton"];
Dean@1362
   558
Dean@1362
   559
                                        break;
Dean@1362
   560
                                    }
Dean@1362
   561
                                case pEpColor.pEpColorRed:
Dean@1298
   562
                                    {
Dean@1362
   563
                                        // Redo handshake with confirmation
Dean@1362
   564
                                        item.TextButton = pEp.Properties.Resources.PrivacyStatus_Handshake;
Dean@1362
   565
                                        item.IsButtonVisible = true;
Dean@1362
   566
                                        item.ButtonOnClick = (x, y) => { this.DoHandshakeForMistrustedKey(myIdentity.Copy(), partnerIdentity.Copy()); };
Dean@1298
   567
Dean@1362
   568
                                        item.IsExpandable = false;
Dean@1298
   569
Dean@1362
   570
                                        break;
Dean@1362
   571
                                    }
Dean@1362
   572
                                default:
Dean@1362
   573
                                    {
Dean@1362
   574
                                        item.IsButtonVisible = false;
Dean@1362
   575
                                        item.IsExpandable = false;
Dean@1362
   576
                                        break;
Dean@1362
   577
                                    }
Dean@1298
   578
                            }
Dean@485
   579
                        }
Dean@366
   580
                    }
Dean@1298
   581
                    else // Invalid identity
Dean@1298
   582
                    {
Dean@1298
   583
                        item = new SelectionItem();
Dean@1348
   584
                        item.TextLine1 = ident.UserName;
Dean@1298
   585
                        item.TextLine2 = ident.Address;
Dean@1298
   586
                        item.ItemImage = null;
Dean@1298
   587
                        item.IsTwoTextLinesVisible = true;
Dean@1298
   588
                        item.IsButtonVisible = false;
Dean@1298
   589
                    }
Dean@1298
   590
Dean@1298
   591
                    managerState.Identities.Add(item);
Dean@1298
   592
                    currIndex++;
Dean@259
   593
                }
Dean@259
   594
Dean@1298
   595
                // Attempt to select and expand the first identity requiring a handshake
Dean@1298
   596
                for (int i = 0; i < managerState.Identities.Count; i++)
Dean@375
   597
                {
Dean@1298
   598
                    // Determine if it's a handshake identity by checking if it's expandable
Dean@1298
   599
                    if (managerState.Identities[i].IsExpandable)
Dean@1298
   600
                    {
Dean@1298
   601
                        managerState.Identities[i].TextButton = Properties.Resources.PrivacyStatus_HandshakeAdvanced;
Dean@1298
   602
                        managerState.Identities[i].IsExpanded = true;
Dean@1298
   603
                        managerState.SelectedIdentityIndex = i;
Dean@1298
   604
                        break;
Dean@1298
   605
                    }
Dean@375
   606
                }
Dean@375
   607
            }
Dean@375
   608
Dean@279
   609
            return (managerState);
Dean@279
   610
        }
Dean@279
   611
Dean@279
   612
        /// <summary>
Dean@279
   613
        /// Builds the latest state of the encryption status manager then shows the UI.
Dean@279
   614
        /// </summary>
Dean@279
   615
        private void BuildAndShowManager()
Dean@279
   616
        {
Dean@279
   617
            DialogResult result;
Dean@313
   618
            FormManagePrivacyStatus form;
Dean@279
   619
Dean@483
   620
            try
Dean@483
   621
            {
Dean@483
   622
                // Show the form
Dean@483
   623
                form = new FormManagePrivacyStatus();
Dean@1082
   624
                form.StartPosition = FormStartPosition.CenterParent;
Dean@1021
   625
                form.FormClosed += ManagerForm_FormClosed;
Dean@1073
   626
                form.FormControl.DisplayState = this.GetManagerState();
Dean@259
   627
Dean@483
   628
                this.managerForm = form;
Dean@1073
   629
                result = form.ShowDialog(this.ParentForm);
Dean@483
   630
            }
Dean@483
   631
            catch (Exception ex)
Dean@483
   632
            {
Dean@860
   633
                Globals.StopAndSendCrashReport(ex);
Dean@483
   634
            }
Dean@259
   635
Dean@259
   636
            return;
Dean@259
   637
        }
Dean@259
   638
Dean@259
   639
        /// <summary>
Dean@1130
   640
        /// Schedules for the pEp rating and UI (including displayed mirror) to be updated.
Dean@1001
   641
        /// This can be called many times with no issue as the update is only run every n milliseconds.
Dean@179
   642
        /// </summary>
Dean@1130
   643
        public void RequestRatingAndUIUpdate()
Dean@1001
   644
        {
Dean@1001
   645
            this.TimerRefresh.Enabled = true;
Dean@1001
   646
            return;
Dean@1001
   647
        }
Dean@1001
   648
Dean@1001
   649
        /// <summary>
Dean@1130
   650
        /// Immediately starts the update of UI rating based on the associated mail item.
Dean@1001
   651
        /// This will start decryption as necessary and also will update the displayed mirror.
Dean@1001
   652
        /// This method by-passes the refresh timer completely.
Dean@1001
   653
        /// WARNING: This method assumes the message is fully downloaded already.
Dean@1001
   654
        /// </summary>
Dean@1130
   655
        private void ImmediateRatingAndUIUpdate()
Dean@159
   656
        {
Dean@173
   657
            if (this.associatedMailItem != null)
Dean@159
   658
            {
Dean@1301
   659
                Log.Verbose("ImmediateRatingAndUIUpdate: Starting processing.");
Dean@740
   660
Dean@1301
   661
                // Start the rating calculation/decryption process
Dean@1301
   662
                this.associatedMailItem.StartProcessing();
Dean@159
   663
            }
Dean@159
   664
Dean@179
   665
            return;
Dean@159
   666
        }
Dean@159
   667
Dean@709
   668
        /// <summary>
Dean@1117
   669
        /// Immediately update the manage privacy status form display state.
Dean@1117
   670
        /// This by default will completely rebuild the display state.
Dean@1117
   671
        /// </summary>
Dean@1130
   672
        /// <param name="onlyRating">True to update only the rating, false to rebuild the entire display state.</param>
Dean@1130
   673
        private void UpdateManagePrivacyStatusForm(bool onlyRating = false)
Dean@1117
   674
        {
Dean@1117
   675
            if (this.managerForm != null)
Dean@1117
   676
            {
Dean@1130
   677
                if (onlyRating)
Dean@1117
   678
                {
Dean@1130
   679
                    // Only update the message rating
Dean@1130
   680
                    this.managerForm.FormControl.DisplayState.Rating = this.FormControlPrivacyStatusChild.DisplayState.Rating;
Dean@1117
   681
                }
Dean@1117
   682
                else
Dean@1117
   683
                {
Dean@1117
   684
                    // Rebuild the entire display state which will update any identity changes
Dean@1117
   685
                    this.managerForm.FormControl.DisplayState = this.GetManagerState();
Dean@1117
   686
                }
Dean@1117
   687
            }
Dean@1117
   688
Dean@1117
   689
            return;
Dean@1117
   690
        }
Dean@1117
   691
Dean@1117
   692
        /// <summary>
Dean@709
   693
        /// Clears the associated unencrypted preview and displays the given note (if any).
Dean@709
   694
        /// </summary>
Dean@709
   695
        /// <param name="note">The note to diplsay.</param>
Dean@709
   696
        private void ClearPreview(string note = null)
Dean@709
   697
        {
Dean@987
   698
            WindowFormRegionCollection formRegions = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveWindow()];
Dean@709
   699
Dean@709
   700
            if ((formRegions != null) &&
Dean@709
   701
                (formRegions.FormRegionPreviewUnencrypted != null) &&
Dean@709
   702
                (formRegions.FormRegionPreviewUnencrypted.Visible))
Dean@709
   703
            {
Dean@709
   704
                formRegions.FormRegionPreviewUnencrypted.ClearMessage();
Dean@709
   705
                formRegions.FormRegionPreviewUnencrypted.SetNote(note);
Dean@709
   706
            }
Dean@709
   707
Dean@709
   708
            return;
Dean@709
   709
        }
Dean@709
   710
Dean@159
   711
        /**************************************************************
Dean@159
   712
         * 
Dean@159
   713
         * Event Handling
Dean@159
   714
         * 
Dean@159
   715
         *************************************************************/
Dean@159
   716
Dean@159
   717
        /// <summary>
Dean@680
   718
        /// Event handler that is called when the form region is displayed.
Dean@1211
   719
        /// This is called each time the form region looses then regains visibility 
Dean@680
   720
        /// (for example an other email is selected then back to this one).
Dean@159
   721
        /// </summary>
Dean@312
   722
        private void FormRegionPrivacyStatus_FormRegionShowing(object sender, System.EventArgs e)
Dean@159
   723
        {
Dean@1169
   724
            bool setByCache = false;
Dean@1197
   725
            PEPIdentity currIdent;
Dean@1197
   726
            Globals.ReturnStatus sts;
Dean@1197
   727
            Outlook.MailItem omi = null;
Dean@1197
   728
            Outlook.Recipient currUser = null;
Dean@1197
   729
            Outlook.Account currAccount = null;
Dean@1197
   730
            Outlook.Account sendingAccount = null;
Dean@1197
   731
            Outlook.NameSpace ns = Globals.ThisAddIn.Application.Session;
Dean@1169
   732
Dean@680
   733
            // Do not allow initialization more than once
Dean@680
   734
            if (initialized == false)
Dean@680
   735
            {
Dean@680
   736
                this.SetAssociatedMailItem();
Dean@173
   737
Dean@1197
   738
                /* It's possible for new draft MailItems to be created outside the context of an account.
Dean@1197
   739
                 * In this situation the SendUsingAccount will always be null which of course breaks several pEp operations.
Dean@1197
   740
                 * The operations themselves cannot make the assumption about what account information to use.
Dean@1197
   741
                 * Therefore, the situation is detected here and for draft mail items a null SendUsingAccount will be 
Dean@1198
   742
                 * set with the session's default account.
Dean@1197
   743
                 */
Dean@1197
   744
                try
Dean@1197
   745
                {
Dean@1303
   746
                    if ((this.OutlookItem is Outlook.MailItem) &&
Dean@1303
   747
                        ((Outlook.MailItem)this.OutlookItem).GetIsDraft())
Dean@1197
   748
                    {
Dean@1303
   749
                        omi = this.OutlookItem as Outlook.MailItem;
Dean@1197
   750
                        sendingAccount = omi.SendUsingAccount;
Dean@1197
   751
                        currUser = ns.CurrentUser;
Dean@1197
   752
Dean@1197
   753
                        if (sendingAccount == null)
Dean@1197
   754
                        {
Dean@1202
   755
                            sts = PEPIdentity.Create(currUser, out currIdent);
Dean@1197
   756
Dean@1197
   757
                            if (sts == Globals.ReturnStatus.Success)
Dean@1197
   758
                            {
Dean@1198
   759
                                currAccount = PEPIdentity.GetOwnAccount(currIdent.Address);
Dean@1198
   760
                                omi.SendUsingAccount = currAccount;
Dean@1197
   761
                            }
Dean@1197
   762
                        }
Dean@1197
   763
                    }
Dean@1197
   764
                }
Dean@1197
   765
                catch { }
Dean@1197
   766
                finally
Dean@1197
   767
                {
Dean@1197
   768
                    if (omi != null)
Dean@1197
   769
                    {
Dean@1197
   770
                        Marshal.ReleaseComObject(omi);
Dean@1197
   771
                        omi = null;
Dean@1197
   772
                    }
Dean@1197
   773
Dean@1197
   774
                    if (currUser != null)
Dean@1197
   775
                    {
Dean@1197
   776
                        Marshal.ReleaseComObject(currUser);
Dean@1197
   777
                        currUser = null;
Dean@1197
   778
                    }
Dean@1197
   779
Dean@1197
   780
                    if (currAccount != null)
Dean@1197
   781
                    {
Dean@1197
   782
                        Marshal.ReleaseComObject(currAccount);
Dean@1197
   783
                        currAccount = null;
Dean@1197
   784
                    }
Dean@1197
   785
Dean@1197
   786
                    if (sendingAccount != null)
Dean@1197
   787
                    {
Dean@1197
   788
                        Marshal.ReleaseComObject(sendingAccount);
Dean@1197
   789
                        sendingAccount = null;
Dean@1197
   790
                    }
Dean@1197
   791
Dean@1197
   792
                    if (ns != null)
Dean@1197
   793
                    {
Dean@1197
   794
                        Marshal.ReleaseComObject(ns);
Dean@1197
   795
                        ns = null;
Dean@1197
   796
                    }
Dean@1197
   797
                }
Dean@1197
   798
Dean@1136
   799
                // Set reader upgrade link visibility
Dean@1286
   800
                if ((Globals.RELEASE_MODE == Globals.ReleaseMode.Reader) &&
Dean@1286
   801
                    (this.associatedMailItem != null) &&
Dean@1286
   802
                    (this.associatedMailItem.IsDraft))
Dean@1286
   803
                {
Dean@1286
   804
                    this.FormControlPrivacyStatusChild.DisplayState.UpgradeLinkIsVisible = true;
Dean@1286
   805
                }
Dean@1286
   806
                else
Dean@1286
   807
                {
Dean@1286
   808
                    this.FormControlPrivacyStatusChild.DisplayState.UpgradeLinkIsVisible = false;
Dean@1286
   809
                }
Dean@1169
   810
Dean@680
   811
                if (this.associatedMailItem != null)
Dean@680
   812
                {
Dean@1169
   813
                    // Connect cryptable mail item events
Dean@680
   814
                    try
Dean@680
   815
                    {
Dean@680
   816
                        this.associatedMailItem.PropertyChanged += MailItem_PropertyChanged;
Dean@1096
   817
                        this.associatedMailItem.ProcessingCompleted += MailItem_ProcessingCompleted;
Dean@1096
   818
                        this.associatedMailItem.GetMirrorCompleted += MailItem_GetMirrorCompleted;
Dean@682
   819
                        this.associatedMailItem.Send += MailItem_Send;
Dean@680
   820
Dean@1303
   821
                        if (this.associatedMailItem.IsSecurelyStored)
Dean@680
   822
                        {
Dean@680
   823
                            this.associatedMailItem.Open += MailItem_Open;
Dean@680
   824
                        }
Dean@680
   825
                    }
Dean@680
   826
                    catch { }
Dean@1169
   827
Dean@1169
   828
                    /* For a MailItem being forwarded or replied to it's import to check against the encrypted conversation cache.
Dean@1169
   829
                     * This is normally done within CryptableMailItem_EncryptedConversationCacheUpdated; however,
Dean@1169
   830
                     * for trusted servers that use an in-line reponse, the EncryptedConversationCacheUpdated event occurs
Dean@1169
   831
                     * BEFORE the new mail item is created. This means it never sees the event.
Dean@1169
   832
                     * To get around this issue, when the form region is first shown, also check if the mail item
Dean@1170
   833
                     * exists in the encrypted conversation cache and should be marked as formerly encrypted.
Dean@1169
   834
                     * If this check passes, never event connect the CryptableMailItem_EncryptedConversationCacheUpdated event.
Dean@1169
   835
                     */
Dean@1169
   836
                    setByCache = this.associatedMailItem.SetIsOriginallyEncryptedByCache();
Dean@680
   837
                }
Dean@680
   838
Dean@1086
   839
                // Connect events
Dean@1169
   840
                if (setByCache == false) { CryptableMailItem.EncryptedConversationCacheUpdated += CryptableMailItem_EncryptedConversationCacheUpdated; }
Dean@1086
   841
                this.FormControlPrivacyStatusChild.PrivacyViewClick += FormControlPrivacyStatusChild_PrivacyViewClick;
Dean@807
   842
Dean@683
   843
                this.TimerRefresh.Tick += TimerRefresh_Tick;
Dean@680
   844
                this.initialized = true;
Dean@179
   845
            }
Dean@159
   846
Dean@683
   847
            // Call the timer tick method manually to refresh data with no delay
Dean@199
   848
            this.TimerRefresh_Tick(null, new EventArgs());
Dean@179
   849
Dean@179
   850
            return;
Dean@159
   851
        }
Dean@159
   852
Dean@159
   853
        /// <summary>
Dean@159
   854
        /// Event handler for when the form region is closed.
Dean@159
   855
        /// </summary>
Dean@312
   856
        private void FormRegionPrivacyStatus_FormRegionClosed(object sender, System.EventArgs e)
Dean@159
   857
        {
Dean@199
   858
            // Disconnect cryptable mail item events
Dean@190
   859
            if (this.associatedMailItem != null)
Dean@179
   860
            {
Dean@179
   861
                try
Dean@179
   862
                {
Dean@445
   863
                    this.associatedMailItem.PropertyChanged -= MailItem_PropertyChanged;
Dean@1096
   864
                    this.associatedMailItem.ProcessingCompleted -= MailItem_ProcessingCompleted;
Dean@1096
   865
                    this.associatedMailItem.GetMirrorCompleted -= MailItem_GetMirrorCompleted;
markus@201
   866
                    this.associatedMailItem.Open -= MailItem_Open;
Dean@682
   867
                    this.associatedMailItem.Send -= MailItem_Send;
Dean@179
   868
                }
Dean@179
   869
                catch { }
Dean@179
   870
            }
Dean@179
   871
Dean@1086
   872
            // Disconnect events
Dean@807
   873
            CryptableMailItem.EncryptedConversationCacheUpdated -= CryptableMailItem_EncryptedConversationCacheUpdated;
Dean@1086
   874
            this.FormControlPrivacyStatusChild.PrivacyViewClick -= FormControlPrivacyStatusChild_PrivacyViewClick;
Dean@807
   875
Dean@682
   876
            // Stop and disconnect the refresh timer
Dean@682
   877
            this.TimerRefresh.Stop();
Dean@682
   878
            this.TimerRefresh.Enabled = false;
Dean@682
   879
            this.TimerRefresh.Tick -= TimerRefresh_Tick;
Dean@682
   880
Dean@179
   881
            return;
Dean@179
   882
        }
Dean@179
   883
Dean@179
   884
        /// <summary>
Dean@179
   885
        /// Event handler called after the refresh timer has elapsed.
Dean@179
   886
        /// </summary>
Dean@179
   887
        private void TimerRefresh_Tick(object sender, EventArgs e)
Dean@179
   888
        {
Dean@199
   889
            bool tryAgain = false;
Dean@684
   890
            bool markForDownload = false;
Dean@179
   891
            this.TimerRefresh.Enabled = false; // Only once
Dean@684
   892
            Outlook.OlDownloadState dlState;
markus@201
   893
Dean@709
   894
            /* The Refresh/UI_Update process is a little more complicated here than other forms.
Dean@709
   895
             * There are the following components:
Dean@709
   896
             *   1. TimerRefresh_Tick
Dean@709
   897
             *        This is the main timer tick event handler called any time
Dean@1130
   898
             *        a refresh was requested (RequestRatingAndUIUpdate) and hasn't been run yet. 
Dean@1001
   899
             *        A refresh is requested either at initialization or when a property changes
Dean@709
   900
             *        (such as MailItem_PropertyChanged). It is on a timer as many 
Dean@709
   901
             *        property change events could occur rapidy, but only one refresh should
Dean@709
   902
             *        occur for performance reasons.
Dean@709
   903
             * 
Dean@1130
   904
             *   2. ImmediateRatingAndUIUpdate
Dean@1307
   905
             *        This will re-calculate the mail item's rating.
Dean@1307
   906
             *        This internally just calls CryptableMailItem.StartProcessing.
Dean@709
   907
             * 
Dean@1130
   908
             *   3. MailItem_ProcessingCompleted
Dean@1307
   909
             *        When processing of the mail item is complete, this even handler will be called.
Dean@1130
   910
             *        This will update the UI with the latest rating then call StartGetMirror.
Dean@709
   911
             *        The CopyStateToUI method is used which means any open privacy status form will also
Dean@709
   912
             *        be updated.
Dean@709
   913
             * 
Dean@709
   914
             *   4. MailItem_GetMirrorComplete
Dean@709
   915
             *        This is the final step in updating the UI, after a mirror is located, it's contents
Dean@1307
   916
             *        will be shown in the unencrypted preview.
Dean@709
   917
             * 
Dean@709
   918
             * The general calling sequence is as shown above 1->4 with each component calling the next.
Dean@709
   919
             * However, for methods that update the mail item directly, commonly only 2->4 is needed.
Dean@709
   920
             */
Dean@709
   921
Dean@179
   922
            // Ensure the tick method is not called more than once
Dean@179
   923
            if (refreshOngoing == false)
Dean@179
   924
            {
Dean@179
   925
                this.refreshOngoing = true;
Dean@179
   926
Dean@179
   927
                if (this.associatedMailItem != null)
Dean@179
   928
                {
Dean@684
   929
                    // Attempt to get the download state
Dean@684
   930
                    try
Dean@684
   931
                    {
Dean@684
   932
                        dlState = this.associatedMailItem.DownloadState;
Dean@684
   933
                    }
Dean@684
   934
                    catch (Exception ex)
Dean@684
   935
                    {
Dean@1249
   936
                        Log.Warning("TimerRefresh_Tick: Get DownloadState failed, " + ex.ToString());
Dean@684
   937
Dean@684
   938
                        // Assume everything is downloaded, but try to download again as well
Dean@684
   939
                        dlState = Outlook.OlDownloadState.olFullItem;
Dean@684
   940
                        markForDownload = true;
Dean@684
   941
                    }
Dean@684
   942
Dean@684
   943
                    if (dlState == Outlook.OlDownloadState.olFullItem)
Dean@179
   944
                    {
Dean@1130
   945
                        this.ImmediateRatingAndUIUpdate();
Dean@179
   946
                    }
Dean@179
   947
                    else
Dean@179
   948
                    {
Dean@684
   949
                        markForDownload = true;
Dean@684
   950
                    }
Dean@684
   951
Dean@684
   952
                    if (markForDownload)
Dean@684
   953
                    {
Dean@684
   954
                        // Try to mark the message for full download
Dean@684
   955
                        try
Dean@684
   956
                        {
Dean@684
   957
                            this.associatedMailItem.MarkForDownload = Outlook.OlRemoteStatus.olMarkedForDownload;
Dean@684
   958
                            tryAgain = true;
Dean@684
   959
                        }
Dean@684
   960
                        catch (Exception ex)
Dean@684
   961
                        {
Dean@1249
   962
                            Log.Warning("TimerRefresh_Tick: MarkForDownload failed, " + ex.ToString());
Dean@684
   963
                        }
Dean@179
   964
                    }
Dean@179
   965
                }
Dean@179
   966
Dean@199
   967
                // Set the timer to refresh again later automatically
Dean@199
   968
                if (tryAgain)
Dean@199
   969
                {
Dean@199
   970
                    this.TimerRefresh.Interval = 100;
Dean@199
   971
                    this.TimerRefresh.Enabled = true;
Dean@199
   972
                }
Dean@199
   973
Dean@179
   974
                this.refreshOngoing = false;
Dean@179
   975
            }
Dean@175
   976
Dean@159
   977
            return;
Dean@159
   978
        }
Dean@159
   979
Dean@169
   980
        /// <summary>
Dean@1096
   981
        /// Event handler for when the processing is completed in the associated mail item.
Dean@709
   982
        /// This will then update the form region UI and the privacy status window as needed.
Dean@680
   983
        /// </summary>
Dean@1096
   984
        private void MailItem_ProcessingCompleted(object sender, CryptableMailItem.ProcessingCompletedEventArgs e)
Dean@680
   985
        {
Dean@1249
   986
            Log.Verbose("MailItem_ProcessingComplete: Decryption completed.");
Dean@740
   987
Dean@680
   988
            try
Dean@680
   989
            {
Dean@680
   990
                // Marshal code back to UI thread as necessary
Dean@680
   991
                this.Invoke(new Action(() =>
Dean@680
   992
                    {
Dean@1130
   993
                        this.FormControlPrivacyStatusChild.DisplayState.Rating = e.Rating;
Dean@1130
   994
                        this.UpdateManagePrivacyStatusForm(true); // Only update the rating
Dean@709
   995
Dean@709
   996
                        /* Create the unencrypted preview if the mail item is encrypted and
Dean@709
   997
                         * it is in an encrypted (untrusted) store
Dean@709
   998
                         * 
Dean@709
   999
                         * This is done here because FormRegionPrivacyStatus has the cryptable mail item and
Dean@709
  1000
                         * it also is initialized after FormRegionPreviewUnencrypted.
Dean@709
  1001
                         */
Dean@747
  1002
                        try
Dean@709
  1003
                        {
Dean@1303
  1004
                            if (this.associatedMailItem.IsSecurelyStored)
Dean@747
  1005
                            {
Dean@1249
  1006
                                Log.Verbose("MailItem_ProcessingComplete: Starting mirror location.");
Dean@747
  1007
                                this.associatedMailItem.StartGetMirror();
Dean@747
  1008
                            }
Dean@747
  1009
                            else
Dean@747
  1010
                            {
Dean@747
  1011
                                this.ClearPreview();
Dean@747
  1012
                            }
Dean@709
  1013
                        }
Dean@747
  1014
                        catch (Exception ex)
Dean@719
  1015
                        {
Dean@747
  1016
                            // Error is possible in some situations where the mail item was deleted or moved while decryption was ongoing.
Dean@747
  1017
                            // While rare, just log the issue and stop the process
Dean@1249
  1018
                            Log.Warning("MailItem_ProcessingComplete: Failed to start mirror location, " + ex.ToString());
Dean@719
  1019
                        }
Dean@680
  1020
                    }));
Dean@680
  1021
            }
Dean@680
  1022
            catch (Exception ex)
Dean@680
  1023
            {
Dean@1249
  1024
                Log.Error("MailItem_ProcessingComplete: Error setting UI state, " + ex.ToString());
Dean@680
  1025
            }
Dean@680
  1026
Dean@680
  1027
            return;
Dean@680
  1028
        }
Dean@680
  1029
Dean@680
  1030
        /// <summary>
Dean@709
  1031
        /// Event handler for when the get mirror locating process is complete for the associated mail item.
Dean@709
  1032
        /// This will then update the unencrypted preview in the UI.
Dean@709
  1033
        /// </summary>
Dean@1096
  1034
        private void MailItem_GetMirrorCompleted(object sender, CryptableMailItem.GetMirrorCompletedEventArgs e)
Dean@709
  1035
        {
Dean@709
  1036
            try
Dean@709
  1037
            {
Dean@709
  1038
                // Marshal code back to UI thread as necessary
Dean@709
  1039
                this.Invoke(new Action(() =>
Dean@709
  1040
                    {
Dean@987
  1041
                        WindowFormRegionCollection formRegions = Globals.FormRegions[Globals.ThisAddIn.Application.ActiveWindow()];
Dean@709
  1042
Dean@910
  1043
                        if ((e.Mirror == null) &&
Dean@1353
  1044
                            (this.associatedMailItem.LastProcessedStatus == Globals.ReturnStatus.Failure))
Dean@1014
  1045
                        {
Dean@1014
  1046
                            this.ClearPreview(Properties.Resources.Message_OpenError);
Dean@1249
  1047
                            Log.Verbose("MailItem_GetMirrorComplete: Cannot display mirror, failure during decryption.");
Dean@1014
  1048
                        }
Dean@1014
  1049
                        else if ((e.Mirror == null) &&
Dean@1353
  1050
                                 (this.associatedMailItem.LastProcessedStatus == Globals.ReturnStatus.FailureNoConnection))
Dean@709
  1051
                        {
Dean@910
  1052
                            this.ClearPreview(Properties.Resources.Message_DecryptionNoConnection);
Dean@1249
  1053
                            Log.Verbose("MailItem_GetMirrorComplete: Cannot display mirror, connection failure during decryption.");
Dean@910
  1054
                        }
Dean@910
  1055
                        else
Dean@910
  1056
                        {
Dean@910
  1057
                            if ((formRegions != null) &&
Dean@910
  1058
                                (formRegions.FormRegionPreviewUnencrypted != null) &&
Dean@910
  1059
                                (formRegions.FormRegionPreviewUnencrypted.Visible))
Dean@910
  1060
                            {
Dean@910
  1061
                                formRegions.FormRegionPreviewUnencrypted.SetMessage(e.Mirror);
Dean@1249
  1062
                                Log.Verbose("MailItem_GetMirrorComplete: Mirror found and displayed.");
Dean@910
  1063
                            }
Dean@709
  1064
                        }
Dean@758
  1065
Dean@758
  1066
                        // Display the mirror if necessary
Dean@758
  1067
                        if ((this.associatedMailItem != null) &&
Dean@758
  1068
                            (this.displayMirrorRequested))
Dean@758
  1069
                        {
Dean@758
  1070
                            this.associatedMailItem.DisplayMirror();
Dean@758
  1071
                            this.displayMirrorRequested = false;
Dean@758
  1072
                        }
Dean@709
  1073
                    }));
Dean@709
  1074
            }
Dean@709
  1075
            catch (Exception ex)
Dean@709
  1076
            {
Dean@1249
  1077
                Log.Error("MailItem_GetMirrorComplete: Error displaying preview, " + ex.ToString());
Dean@709
  1078
            }
Dean@709
  1079
Dean@709
  1080
            return;
Dean@709
  1081
        }
Dean@709
  1082
Dean@709
  1083
        /// <summary>
Dean@807
  1084
        /// Event handler for the static mail item encrypted conversation cache updated.
Dean@807
  1085
        /// This event is fired after the conversation cache has been updated with parent information following a
Dean@807
  1086
        /// forward or reply mail item event (on a different, likely parent, mail item).
Dean@807
  1087
        /// </summary>
Dean@807
  1088
        private void CryptableMailItem_EncryptedConversationCacheUpdated(object sender, EventArgs e)
Dean@807
  1089
        {
Dean@807
  1090
            // Process the mail item now that the cache is updated
Dean@807
  1091
            this.associatedMailItem.SetIsOriginallyEncryptedByCache();
Dean@807
  1092
Dean@807
  1093
            // Remove the event handler -- this can only be processed once because it's timing dependent
Dean@807
  1094
            CryptableMailItem.EncryptedConversationCacheUpdated -= CryptableMailItem_EncryptedConversationCacheUpdated;
Dean@807
  1095
Dean@807
  1096
            return;
Dean@807
  1097
        }
Dean@807
  1098
Dean@807
  1099
        /// <summary>
Dean@169
  1100
        /// Event handler for when a mail item is being opened in an inspector.
Dean@180
  1101
        /// See: https://msdn.microsoft.com/en-us/library/office/ff865989.aspx
Dean@169
  1102
        /// </summary>
Dean@169
  1103
        /// <param name="cancel">Whether to cancel the event: Value is False when the event occurs. 
Dean@169
  1104
        /// If the event procedure sets this argument to True, the open operation is not completed 
Dean@169
  1105
        /// and the inspector is not displayed.</param>
Dean@169
  1106
        private void MailItem_Open(ref bool cancel)
Dean@159
  1107
        {
Dean@758
  1108
            bool result;
Dean@758
  1109
Dean@758
  1110
            if (this.associatedMailItem != null &&
Dean@1303
  1111
                this.associatedMailItem.IsSecurelyStored)
Dean@169
  1112
            {
Dean@758
  1113
                // Try to open the mirror
Dean@758
  1114
                result = this.associatedMailItem.DisplayMirror();
Dean@758
  1115
Dean@758
  1116
                if (result == false)
Dean@758
  1117
                {
Dean@758
  1118
                    // Set flag to open after decryption/mirror location
Dean@758
  1119
                    this.displayMirrorRequested = true;
Dean@758
  1120
                }
Dean@758
  1121
Dean@758
  1122
                // Always cancel opening the original
Dean@169
  1123
                cancel = true;
Dean@169
  1124
            }
Dean@169
  1125
Dean@169
  1126
            return;
Dean@159
  1127
        }
Dean@159
  1128
Dean@169
  1129
        /// <summary>
Dean@682
  1130
        /// Event handler for when a mail item is sent.
Dean@682
  1131
        /// See: https://msdn.microsoft.com/en-us/library/office/ff865379.aspx
Dean@682
  1132
        /// </summary>
Dean@682
  1133
        /// <param name="cancel">Whether to cancel the event: Value is False when the event occurs. 
Dean@682
  1134
        /// If the event procedure sets this argument to True, the send operation is not completed 
Dean@682
  1135
        /// and the inspector is left open.</param>
Dean@682
  1136
        private void MailItem_Send(ref bool cancel)
Dean@682
  1137
        {
Dean@807
  1138
            DialogResult result;
Dean@807
  1139
Dean@1170
  1140
            if ((Globals.ThisAddIn.Settings.IsSecurityLossWarningEnabled) &&
Dean@1170
  1141
                (this.associatedMailItem.IsOriginallyEncrypted) &&
markus@1337
  1142
                (this.FormControlPrivacyStatusChild.DisplayState.Rating < pEpRating.pEpRatingUnreliable))
Dean@807
  1143
            {
Thomas@1318
  1144
Thomas@1318
  1145
#if READER_RELEASE_MODE
Thomas@1318
  1146
                FormReaderSplash warningMessage = new FormReaderSplash(true);
Thomas@1318
  1147
                result = warningMessage.ShowDialog();
Thomas@1318
  1148
Thomas@1318
  1149
                if (result != DialogResult.OK)
Thomas@1318
  1150
                {
Thomas@1318
  1151
                    // Cancel sending
Thomas@1318
  1152
                    cancel = true;
Thomas@1318
  1153
                }
Thomas@1318
  1154
#else
Dean@1074
  1155
                result = System.Windows.Forms.MessageBox.Show(this.ParentForm,
Dean@1170
  1156
                                                              pEp.Properties.Resources.Message_WarningSecurityLoss,
Dean@1074
  1157
                                                              pEp.Properties.Resources.Message_TitleConfirmOperation,
Dean@1169
  1158
                                                              MessageBoxButtons.YesNo,
Dean@1169
  1159
                                                              MessageBoxIcon.Warning);
Dean@807
  1160
Dean@807
  1161
                if (result == DialogResult.No)
Dean@807
  1162
                {
Dean@807
  1163
                    // Cancel sending
Dean@807
  1164
                    cancel = true;
Dean@807
  1165
                }
Thomas@1318
  1166
#endif
Dean@807
  1167
            }
Dean@807
  1168
Dean@682
  1169
            // Stop and disconnect the refresh timer
Dean@682
  1170
            // This is necessary so an ongoing refresh doesn't try to access a mail item as it's being moved
Dean@807
  1171
            if (cancel == false)
Dean@807
  1172
            {
Dean@807
  1173
                this.TimerRefresh.Stop();
Dean@807
  1174
                this.TimerRefresh.Enabled = false;
Dean@807
  1175
                this.TimerRefresh.Tick -= TimerRefresh_Tick;
Dean@807
  1176
            }
Dean@682
  1177
Dean@682
  1178
            return;
Dean@682
  1179
        }
Dean@682
  1180
Dean@682
  1181
        /// <summary>
Dean@169
  1182
        /// Event handler for when a mail item property is changed.
Dean@169
  1183
        /// See: https://msdn.microsoft.com/en-us/library/office/ff866739.aspx
Dean@169
  1184
        /// </summary>
Dean@169
  1185
        /// <param name="propertyName">The name of the property that was changed.</param>
Dean@445
  1186
        private void MailItem_PropertyChanged(object sender, PropertyChangedEventArgs e)
Dean@159
  1187
        {
Dean@1349
  1188
            switch (e.PropertyName.ToUpperInvariant())
Dean@159
  1189
            {
Dean@179
  1190
                case "TO":
Dean@1130
  1191
                    this.RequestRatingAndUIUpdate();
Dean@159
  1192
                    break;
Dean@1106
  1193
                    // Outlook bug: there are always both events, so one is enough
Dean@1106
  1194
                    //case "CC":
Dean@1130
  1195
                    //    this.RequestRatingAndUIUpdate();
Dean@1106
  1196
                    //    break;
Dean@159
  1197
            }
Dean@169
  1198
Dean@169
  1199
            return;
Dean@159
  1200
        }
Dean@159
  1201
Dean@179
  1202
        /// <summary>
Dean@1021
  1203
        /// Event handler for when the manager form is closed.
Dean@1021
  1204
        /// </summary>
Dean@1021
  1205
        private void ManagerForm_FormClosed(object sender, FormClosedEventArgs e)
Dean@1021
  1206
        {
Dean@1021
  1207
            // Remove the reference held in the FormRegionPrivacyStatus so it stops getting updated
Dean@1021
  1208
            if (this.managerForm != null)
Dean@1021
  1209
            {
Dean@1021
  1210
                this.managerForm.FormClosed -= ManagerForm_FormClosed;
Dean@1021
  1211
                this.managerForm = null;
Dean@1021
  1212
            }
Dean@1021
  1213
Dean@1021
  1214
            return;
Dean@1021
  1215
        }
Dean@1021
  1216
Dean@1021
  1217
        /// <summary>
Dean@859
  1218
        /// Event handler for when the pEp website hyperlink is clicked.
Dean@859
  1219
        /// </summary>
Dean@859
  1220
        private void LinkLabelUpgrade_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
Dean@859
  1221
        {
Dean@966
  1222
            try
Dean@966
  1223
            {
Dean@1007
  1224
                Process.Start(Globals.PEP_WEBSITE_UPGRADE_LINK);
Dean@966
  1225
            }
Dean@966
  1226
            catch (Exception ex)
Dean@966
  1227
            {
Dean@1249
  1228
                Log.Error("LinkLabelUpgrade_LinkClicked: Unable to open website link, " + ex.ToString());
Dean@966
  1229
            }
Dean@966
  1230
Dean@859
  1231
            return;
Dean@859
  1232
        }
Dean@1047
  1233
Dean@1047
  1234
        /// <summary>
Dean@1086
  1235
        /// Event handler for when the privacy view button is clicked within the form control.
Dean@1047
  1236
        /// </summary>
Dean@1086
  1237
        private void FormControlPrivacyStatusChild_PrivacyViewClick(object sender, System.Windows.RoutedEventArgs e)
Dean@1047
  1238
        {
Dean@1130
  1239
            this.RequestRatingAndUIUpdate();
Dean@1047
  1240
            this.BuildAndShowManager();
Dean@1047
  1241
            return;
Dean@1047
  1242
        }
vb@133
  1243
    }
vb@133
  1244
}