Show sync handshake dialogs on separate STA thread sync
authorThomas
Thu, 18 Apr 2019 14:04:00 +0200
branchsync
changeset 2617d0fa927c6a46
parent 2616 b9e529090877
child 2618 5c8112dd3230
Show sync handshake dialogs on separate STA thread
AdapterCallbacks.cs
     1.1 --- a/AdapterCallbacks.cs	Mon Apr 15 15:35:42 2019 +0200
     1.2 +++ b/AdapterCallbacks.cs	Thu Apr 18 14:04:00 2019 +0200
     1.3 @@ -2,6 +2,8 @@
     1.4  using pEpCOMServerAdapterLib;
     1.5  using System;
     1.6  using System.Runtime.InteropServices;
     1.7 +using System.Threading;
     1.8 +using System.Threading.Tasks;
     1.9  using System.Windows.Forms;
    1.10  using Outlook = Microsoft.Office.Interop.Outlook;
    1.11  
    1.12 @@ -9,20 +11,15 @@
    1.13  {
    1.14      /// <summary>
    1.15      /// Callback implementation for the events the pEpEngine fires.
    1.16 -    /// </summary>
    1.17 -    /// <remarks>We need to have this in a class
    1.18 -    /// deriving from <see cref="StandardOleMarshalObject"/>, as this guarantees that the calls
    1.19 -    /// are scheduled on the primary thread. We're using a callback interface instead of events
    1.20 -    /// because it seems difficult to marshal complex datatypes (structs) for COM events, the
    1.21 -    /// default glue code generated by the VS wizard is not up to the task.
    1.22 -    /// </remarks>
    1.23 -    internal class AdapterCallbacks : StandardOleMarshalObject, IpEpEngineCallbacks
    1.24 +    /// </summary>   
    1.25 +    internal class AdapterCallbacks : IpEpEngineCallbacks
    1.26      {
    1.27 -        private static  HandshakeDialog      handshakeDialog         = null;
    1.28 -        private static  Timer                timer                   = null;
    1.29 -        private const   int                  FAST_POLLING_INTERVAL   = 1000;    // 1 second in ms
    1.30 -        private const   int                  MAX_POLLING_COUNT       = 600;     // 600 times each second => max. 10 minutes
    1.31 +        private static  HandshakeDialog             handshakeDialog         = null;
    1.32 +        private static  System.Windows.Forms.Timer  timer                   = null;
    1.33 +        private const   int                         FAST_POLLING_INTERVAL   = 1000;    // 1 second in ms
    1.34 +        private const   int                         MAX_POLLING_COUNT       = 600;     // 600 times each second => max. 10 minutes      
    1.35  
    1.36 +        #region Callbacks
    1.37          /// <summary>
    1.38          /// Event handler for when the pEp engine requests a handshake during key synchronization.
    1.39          /// </summary>
    1.40 @@ -36,42 +33,18 @@
    1.41          {
    1.42              bool? dialogResult = null;
    1.43              SyncHandshakeResult handshakeResult = SyncHandshakeResult.SyncHandshakeCancel;
    1.44 -            HandshakeDialog.HandshakeMode mode;
    1.45 -            PEPIdentity ownIdentity;
    1.46 -            PEPIdentity partnerIdentity;
    1.47  
    1.48              Log.Verbose("NotifyHandshake: Started with signal " + signal.ToString());
    1.49  
    1.50 -            /* Doublecheck that sync is enabled for this account.
    1.51 -             * Do not show any dialog for accounts with sync disabled.
    1.52 -             */
    1.53 -            bool notForSync = false;
    1.54 -            try
    1.55 -            {
    1.56 -                notForSync = own.Flags.HasFlag(pEpIdentityFlags.pEpIdfNotForSync);
    1.57 -            }
    1.58 -            catch (Exception ex)
    1.59 -            {
    1.60 -                notForSync = false;
    1.61 -                Log.Error("NotifyHandshake: Error reading NotForSync flag. " + ex.ToString());
    1.62 -            }
    1.63 -
    1.64 -            // If sync is disabled, return cancel
    1.65 -            if (notForSync)
    1.66 -            {
    1.67 -                Log.Warning("NotifyHandshake: callback received for account with NotForSync flag. Ignoring request.");
    1.68 -                return handshakeResult;
    1.69 -            }
    1.70 -
    1.71              /* Close handshake dialog if it was still open and the signal type
    1.72               * is not "undefined", in which case the status quo should be preserved.
    1.73               */
    1.74 -            if ((handshakeDialog != null) &&
    1.75 +            if ((AdapterCallbacks.handshakeDialog != null) &&
    1.76                  (signal != SyncHandshakeSignal.SyncNotifyUndefined))
    1.77              {
    1.78                  try
    1.79                  {
    1.80 -                    handshakeDialog.Close();
    1.81 +                    AdapterCallbacks.handshakeDialog.Close();
    1.82                  }
    1.83                  catch (Exception ex)
    1.84                  {
    1.85 @@ -80,8 +53,8 @@
    1.86  
    1.87                  // We set the result in case of an reentrant call, so the
    1.88                  // "parent" also gets the information.
    1.89 -                handshakeDialog.DialogResult = null;
    1.90 -                handshakeDialog = null;
    1.91 +                AdapterCallbacks.handshakeDialog.DialogResult = null;
    1.92 +                AdapterCallbacks.handshakeDialog = null;
    1.93              }
    1.94  
    1.95              // The action to take depends on the given signal
    1.96 @@ -102,49 +75,23 @@
    1.97                          // Syncronize engine with settings just in case (should already be synced)
    1.98                          Globals.ThisAddIn.SyncWithSettings(true);
    1.99  
   1.100 -                        // Ensure identities are updated with fingerprint
   1.101 -                        ownIdentity = new PEPIdentity(ThisAddIn.PEPEngine.Myself(own));
   1.102 -                        partnerIdentity = new PEPIdentity(ThisAddIn.PEPEngine.UpdateIdentity(partner));
   1.103 -
   1.104 -                        // Only the partner color is shown in the UI so get the rating
   1.105 -                        try
   1.106 +                        // If sync is disabled, return cancel
   1.107 +                        if (own.Flags.HasFlag(pEpIdentityFlags.pEpIdfNotForSync))
   1.108                          {
   1.109 -                            partnerIdentity.Rating = ThisAddIn.PEPEngine.IdentityRating(partnerIdentity.ToCOMType());
   1.110 -                        }
   1.111 -                        catch { }
   1.112 -
   1.113 -                        // Specify handshake type
   1.114 -                        mode = HandshakeDialog.HandshakeMode.SyncTypeA;
   1.115 -
   1.116 -                        // Show handshake dialog
   1.117 -                        if (handshakeDialog != null)
   1.118 -                        {
   1.119 -                            try
   1.120 -                            {
   1.121 -                                handshakeDialog.Close();
   1.122 -                            }
   1.123 -                            catch (Exception)
   1.124 -                            {
   1.125 -                                throw;
   1.126 -                            }
   1.127 +                            Log.Warning("NotifyHandshake: callback received for account with NotForSync flag. Ignoring request.");
   1.128 +                            return handshakeResult;
   1.129                          }
   1.130  
   1.131 -                        handshakeDialog = new HandshakeDialog(ownIdentity,
   1.132 -                                                              partnerIdentity,
   1.133 -                                                              mode);
   1.134 -
   1.135 -                        // Build dialog, but only show if building was successful
   1.136 -                        if (handshakeDialog.BuildDialog() &&
   1.137 -                            handshakeDialog?.Items?.Count > 0)
   1.138 +                        // Close handshake dialog if necessary
   1.139 +                        if (AdapterCallbacks.handshakeDialog != null)
   1.140                          {
   1.141 -                            dialogResult = handshakeDialog.ShowDialog();
   1.142 -                        }
   1.143 -                        else
   1.144 -                        {
   1.145 -                            Log.Error("NotifyHandshake: Error creating handshake dialog. Dialog was not shown.");
   1.146 +                            AdapterCallbacks.handshakeDialog.Close();
   1.147                          }
   1.148  
   1.149 -                        handshakeDialog = null;
   1.150 +                        // Show handshake dialog in new STA thread
   1.151 +                        dialogResult = this.ShowHandshakeDialog(new PEPIdentity(own), new PEPIdentity(partner));
   1.152 +
   1.153 +                        AdapterCallbacks.handshakeDialog = null;
   1.154  
   1.155                          // Send result back to the engine
   1.156                          switch (dialogResult)
   1.157 @@ -193,7 +140,7 @@
   1.158  
   1.159              Log.Verbose("NotifyHandshake: Completed, " + handshakeResult.ToString());
   1.160  
   1.161 -            return (handshakeResult);
   1.162 +            return handshakeResult;
   1.163          }
   1.164  
   1.165          /// <summary>
   1.166 @@ -254,7 +201,7 @@
   1.167  
   1.168                  try
   1.169                  {
   1.170 -                    timer = new Timer
   1.171 +                    timer = new System.Windows.Forms.Timer
   1.172                      {
   1.173                          Interval = FAST_POLLING_INTERVAL
   1.174                      };
   1.175 @@ -295,5 +242,93 @@
   1.176                  timer = null;
   1.177              }
   1.178          }
   1.179 +        #endregion
   1.180 +
   1.181 +        #region Helper methods
   1.182 +
   1.183 +        /// <summary>
   1.184 +        /// Wrapper method for the asynchronous call to show the handshake dialog in a separate STA thread.
   1.185 +        /// </summary>
   1.186 +        /// <param name="own">The personal identity for the handshake.</param>
   1.187 +        /// <param name="partner">The communication partner identity for the handshake.</param>
   1.188 +        /// <param name="signal">The reason for the handshake notification.</param>
   1.189 +        /// <returns>The user selected result.</returns>
   1.190 +        public bool? ShowHandshakeDialog(PEPIdentity own, PEPIdentity partner)
   1.191 +        {
   1.192 +            // Show the dialog
   1.193 +            Task<bool?> task = this.ShowHandshakeDialogAsync(own, partner);
   1.194 +
   1.195 +            // Check for exceptions and return result
   1.196 +            if (task.Exception != null)
   1.197 +            {
   1.198 +                Log.Error("ShowHandshakeDialog: Error occured. " + task.Exception);
   1.199 +                return null;
   1.200 +            }
   1.201 +            else
   1.202 +            {
   1.203 +                return task.Result;
   1.204 +            }
   1.205 +        }
   1.206 +
   1.207 +        /// <summary>
   1.208 +        /// Shows the handshake dialog in a separate STA thread and returns the dialog result.
   1.209 +        /// </summary>
   1.210 +        /// <param name="own">The personal identity for the handshake.</param>
   1.211 +        /// <param name="partner">The communication partner identity for the handshake.</param>
   1.212 +        /// <param name="signal">The reason for the handshake notification.</param>
   1.213 +        /// <returns>The user selected result.</returns>
   1.214 +        public async Task<bool?> ShowHandshakeDialogAsync(PEPIdentity own, PEPIdentity partner)
   1.215 +        {
   1.216 +            // Create a new STA thread and show dialog on it
   1.217 +            return await AdapterCallbacks.StartSTATask<bool?>(() =>
   1.218 +            {
   1.219 +                // Create the handshake dialog
   1.220 +                AdapterCallbacks.handshakeDialog = new HandshakeDialog(own,
   1.221 +                                                                       partner,
   1.222 +                                                                       HandshakeDialog.HandshakeMode.SyncTypeA);
   1.223 +
   1.224 +
   1.225 +                // Build dialog, but only show if building was successful
   1.226 +                if (AdapterCallbacks.handshakeDialog.BuildDialog() &&
   1.227 +                    AdapterCallbacks.handshakeDialog?.Items?.Count > 0)
   1.228 +                {
   1.229 +                    return AdapterCallbacks.handshakeDialog.ShowDialog();
   1.230 +                }
   1.231 +                else
   1.232 +                {
   1.233 +                    Log.Error("NotifyHandshake: Error creating handshake dialog. Dialog was not shown.");
   1.234 +                    return null;
   1.235 +                }
   1.236 +            });
   1.237 +        }
   1.238 +        #endregion
   1.239 +
   1.240 +        #region Static methods
   1.241 +
   1.242 +        /// <summary>
   1.243 +        /// Starts a Task on a new STA thread.
   1.244 +        /// </summary>
   1.245 +        /// <typeparam name="T">The return type of the task.</typeparam>
   1.246 +        /// <param name="func">The function this task has to complete.</param>
   1.247 +        /// <returns>The created task.</returns>
   1.248 +        public static Task<T> StartSTATask<T>(Func<T> func)
   1.249 +        {
   1.250 +            TaskCompletionSource<T> tcs = new TaskCompletionSource<T>();
   1.251 +            Thread thread = new Thread(() =>
   1.252 +            {
   1.253 +                try
   1.254 +                {
   1.255 +                    tcs.SetResult(func());
   1.256 +                }
   1.257 +                catch (Exception ex)
   1.258 +                {
   1.259 +                    tcs.SetException(ex);
   1.260 +                }
   1.261 +            });
   1.262 +            thread.SetApartmentState(ApartmentState.STA);
   1.263 +            thread.Start();
   1.264 +            return tcs.Task;
   1.265 +        }
   1.266 +        #endregion
   1.267      }
   1.268  }