Exemple #1
0
 // Reads the characteristic's value and calls the completion with the characteristic's value.
 // If there is a pending write request on the same characteristic, the read is ignored to prevent "UI glitching".
 public void CharacteristicCellReadInitialValueForCharacteristic(CharacteristicCell cell, HMCharacteristic characteristic, Action <NSObject, NSError> completion)
 {
     characteristic.ReadValue(error => updateQueue.DispatchSync(() => {
         NSObject sentValue;
         if (sentWrites.TryGetValue(characteristic, out sentValue))
         {
             completion(sentValue, null);
             return;
         }
         DispatchQueue.MainQueue.DispatchAsync(() => completion(characteristic.Value, error));
     }));
 }
 public override void RenderContextChanged(AVVideoCompositionRenderContext newRenderContext)
 {
     renderContextQueue.DispatchSync(() => {
         renderContext          = newRenderContext;
         renderContextDidChange = true;
     });
 }
Exemple #3
0
        public bool TogglePlay()
        {
            stateChangeQueue.DispatchSync(() => {
                if (isPlaying)
                {
                    player.Stop();
                    engine.Stop();
                    isPlaying = false;

                    SetSessionActive(false);
                }
                else
                {
                    SetSessionActive(true);

                    ScheduleLoop();
                    ScheduleLoop();

                    NSError error;
                    if (!engine.StartAndReturnError(out error))
                    {
                        Console.WriteLine(error.LocalizedDescription);
                    }

                    player.Play();
                    isPlaying = true;
                }
            });

            return(isPlaying);
        }
Exemple #4
0
        private void Dispose(bool finalizing)
        {
            if (!finalizing)
            {
                DispatchQueue.DispatchSync(() =>
                {
                    if (_disposed)
                    {
                        return;
                    }

                    _nativeParams?.Dispose();
                    Config.Options.Dispose();
                    if (Status.Activity != ReplicatorActivityLevel.Stopped)
                    {
                        var newStatus = new ReplicatorStatus(ReplicatorActivityLevel.Stopped, Status.Progress, null);
                        _statusChanged.Fire(this, new ReplicatorStatusChangedEventArgs(newStatus));
                        Status = newStatus;
                    }

                    Stop();
                    Native.c4repl_free(_repl);
                    _repl     = null;
                    _disposed = true;
                });
            }
            else
            {
                Native.c4repl_free(_repl);
                _repl = null;
            }
        }
Exemple #5
0
        /// <summary>
        /// Checks whether or not a document with the given ID has any pending revisions to push
        /// </summary>
        /// <param name="documentID">The document ID</param>
        /// <returns>A bool which represents whether or not the document with the corresponding ID has one or more pending revisions.
        /// <c>true</c> means that one or more revisions have not been pushed to the remote yet,
        /// and <c>false</c> means that all revisions on the document have been pushed</returns>
        /// <exception cref="CouchbaseLiteException">Thrown if no push replication</exception>
        /// <exception cref="CouchbaseException">Thrown if an error condition is returned from LiteCore</exception>
        public bool IsDocumentPending([NotNull] string documentID)
        {
            CBDebug.MustNotBeNull(WriteLog.To.Sync, Tag, nameof(documentID), documentID);
            bool isDocPending = false;

            if (!IsPushing())
            {
                CBDebug.LogAndThrow(WriteLog.To.Sync,
                                    new CouchbaseLiteException(C4ErrorCode.Unsupported, CouchbaseLiteErrorMessage.PullOnlyPendingDocIDs),
                                    Tag, CouchbaseLiteErrorMessage.PullOnlyPendingDocIDs, true);
            }

            DispatchQueue.DispatchSync(() => {
                var errSetupRepl = SetupC4Replicator();
                if (errSetupRepl.code > 0)
                {
                    CBDebug.LogAndThrow(WriteLog.To.Sync, CouchbaseException.Create(errSetupRepl), Tag, errSetupRepl.ToString(), true);
                }
            });

            LiteCoreBridge.Check(err =>
            {
                isDocPending = Native.c4repl_isDocumentPending(_repl, documentID, err);
                return(isDocPending);
            });

            return(isDocPending);
        }
Exemple #6
0
        public void DispatchSync()
        {
            TestRuntime.AssertSystemVersion(PlatformName.iOS, 8, 0, throwIfOtherPlatform: false);
            TestRuntime.AssertSystemVersion(PlatformName.MacOSX, 10, 10, throwIfOtherPlatform: false);

            using (var queue = new DispatchQueue("DispatchSync")) {
                var called   = false;
                var callback = new Action(() => called = true);
                queue.DispatchSync(callback);
                Assert.IsTrue(called, "Called");

                called = false;
                using (var dg = new DispatchBlock(callback))
                    queue.DispatchSync(dg);
                Assert.IsTrue(called, "Called DispatchBlock");
            }
        }
        public void CommonApplicationDidFinishLaunching(Action completionHandler)
        {
            Scene.ShowsStatistics = true;
            Scene.BackgroundColor = AppKit.NSColor.Black;

            NSProgress progress = NSProgress.FromTotalUnitCount(10);

            DispatchQueue queue = DispatchQueue.GetGlobalQueue(DispatchQueuePriority.Default);

            queue.DispatchSync(() => {
                progress.BecomeCurrent(2);
                var ui = new InGameScene(Scene.Bounds.Size);

                DispatchQueue.MainQueue.DispatchAsync(() =>
                                                      Scene.OverlayScene = ui
                                                      );

                progress.ResignCurrent();
                progress.BecomeCurrent(3);

                GameSimulation gameSim = GameSimulation.Sim;
                gameSim.GameUIScene    = ui;

                progress.ResignCurrent();
                progress.BecomeCurrent(3);

                SCNTransaction.Flush();

                // Preload
                Scene.Prepare(gameSim, new Func <bool> (() =>
                                                        true
                                                        ));
                progress.ResignCurrent();
                progress.BecomeCurrent(1);

                // Game Play Specific Code
                gameSim.GameUIScene.GameStateDelegate = gameSim.GameLevel;
                gameSim.GameLevel.ResetLevel();
                gameSim.SetGameState(GameState.PreGame);

                progress.ResignCurrent();
                progress.BecomeCurrent(1);

                DispatchQueue.MainQueue.DispatchAsync(() => {
                    Scene.Scene = gameSim;
                    Scene.WeakSceneRendererDelegate = gameSim;

                    if (completionHandler != null)
                    {
                        completionHandler();
                    }
                });

                progress.ResignCurrent();
            });
        }
Exemple #8
0
        /// <summary>
        /// Stops the replication
        /// </summary>
        public void Stop()
        {
            DispatchQueue.DispatchSync(() =>
            {
                StopReachabilityObserver();
                if (_repl != null)
                {
                    if (_rawStatus.level == C4ReplicatorActivityLevel.Stopped ||
                        _rawStatus.level == C4ReplicatorActivityLevel.Stopping)
                    {
                        return;
                    }

                    Native.c4repl_stop(_repl);
                }
            });
        }
Exemple #9
0
        List <Activity> CreateActivityDataWithActivities(CMMotionActivity[] activities, Action completionHandler)
        {
            var results = new List <Activity> ();

            var group = DispatchGroup.Create();
            var queue = new DispatchQueue("resultQueue");

            var filteredActivities = activities.Where(activity => activity.HasActivitySignature() &&
                                                      !activity.Stationary &&
                                                      activity.Confidence != CMMotionActivityConfidence.Low).ToArray <CMMotionActivity> ();

            var activitySegments = FindActivitySegments(filteredActivities);

            foreach (var segment in activitySegments)
            {
                group.Enter();
                pedometer.QueryPedometerData(segment.Item1.StartDate, (NSDate)segment.Item2, (pedometerData, error) => {
                    queue.DispatchAsync(() => {
                        var activity = new Activity(segment.Item1,
                                                    ((DateTime)segment.Item1.StartDate).ToLocalTime(),
                                                    segment.Item2.ToLocalTime(),
                                                    pedometerData);

                        results.Add(activity);
                    });

                    if (error != null)
                    {
                        HandleError(error);
                    }

                    group.Leave();
                });
            }

            group.Notify(DispatchQueue.MainQueue, () => {
                queue.DispatchSync(() => {
                    RecentActivities = results;
                    RecentActivities.Reverse();
                    completionHandler?.Invoke();
                });
            });

            return(results);
        }
Exemple #10
0
        /// <summary>
        /// Starts the replication with an option to reset the checkpoint.
        /// </summary>
        /// <param name="reset">Resets the local checkpoint of the replicator, meaning that it will read all changes since the beginning
        /// of time from the remote database.
        /// </param>
        public void Start(bool reset)
        {
            var status = default(C4ReplicatorStatus);

            DispatchQueue.DispatchSync(() =>
            {
                if (_disposed)
                {
                    throw new ObjectDisposedException(CouchbaseLiteErrorMessage.ReplicatorDisposed);
                }

                var err = SetupC4Replicator();
                if (err.code > 0)
                {
                    WriteLog.To.Sync.E(Tag, $"Setup replicator {this} failed.");
                }

                if (_repl != null)
                {
                    status = Native.c4repl_getStatus(_repl);
                    if (status.level == C4ReplicatorActivityLevel.Stopped ||
                        status.level == C4ReplicatorActivityLevel.Stopping ||
                        status.level == C4ReplicatorActivityLevel.Offline)
                    {
                        ServerCertificate = null;
                        WriteLog.To.Sync.I(Tag, $"{this}: Starting");
                        Native.c4repl_start(_repl, Config.Options.Reset || reset);
                        Config.Options.Reset = false;
                        Config.Database.AddActiveStoppable(this);
                        status = Native.c4repl_getStatus(_repl);
                    }
                }
                else
                {
                    status = new C4ReplicatorStatus {
                        error    = err,
                        level    = C4ReplicatorActivityLevel.Stopped,
                        progress = new C4Progress()
                    };
                }
            });

            UpdateStateProperties(status);
            DispatchQueue.DispatchSync(() => StatusChangedCallback(status));
        }
Exemple #11
0
        public IImmutableSet <string> GetPendingDocumentIDs()
        {
            var result = new HashSet <string>();

            if (!IsPushing())
            {
                CBDebug.LogAndThrow(WriteLog.To.Sync,
                                    new CouchbaseLiteException(C4ErrorCode.Unsupported, CouchbaseLiteErrorMessage.PullOnlyPendingDocIDs),
                                    Tag, CouchbaseLiteErrorMessage.PullOnlyPendingDocIDs, true);
            }

            DispatchQueue.DispatchSync(() => {
                var errSetupRepl = SetupC4Replicator();
                if (errSetupRepl.code > 0)
                {
                    CBDebug.LogAndThrow(WriteLog.To.Sync, CouchbaseException.Create(errSetupRepl), Tag, errSetupRepl.ToString(), true);
                }
            });

            byte[] pendingDocIds = LiteCoreBridge.Check(err =>
            {
                return(Native.c4repl_getPendingDocIDs(_repl, err));
            });

            if (pendingDocIds != null)
            {
                _databaseThreadSafety.DoLocked(() => {
                    var flval = Native.FLValue_FromData(pendingDocIds, FLTrust.Trusted);
                    var flarr = Native.FLValue_AsArray(flval);
                    var cnt   = (int)Native.FLArray_Count(flarr);
                    for (int i = 0; i < cnt; i++)
                    {
                        var flv = Native.FLArray_Get(flarr, (uint)i);
                        result.Add(Native.FLValue_AsString(flv));
                    }

                    Array.Clear(pendingDocIds, 0, pendingDocIds.Length);
                    pendingDocIds = null;
                });
            }

            _pendingDocIds = result.ToImmutableHashSet <string>();
            return(_pendingDocIds);
        }
Exemple #12
0
        public void ResetWithTagString(string tags)
        {
            // Reloads table with new tag settings
            // First, anything the table is updating with now is potentially invalid, cancel any current updates
            fetchRecordQueue.CancelAllOperations();
            // This should only be filled with array add operations, best to just wait for it to finish
            updateCellArrayQueue.DispatchSync(() => {
            });

            // Resets the table to be empty
            PostCells.Clear();
            lastPostSeenOnServer = null;
            reloadHandler();

            // Sets tag array and prepares table for initial update
            tagArray = string.IsNullOrWhiteSpace(tags)
                                ? new string[0]
                                : tags.ToLower().Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);

            postCursor     = null;
            isLoadingBatch = false;
            haveOldestPost = false;
            LoadBatch();
        }
Exemple #13
0
        private C4Error SetupC4Replicator()
        {
            Config.Database.CheckOpenLocked();
            C4Error err = new C4Error();

            if (_repl != null)
            {
                Native.c4repl_setOptions(_repl, ((FLSlice)Config.Options.FLEncode()).ToArrayFast());
                return(err);
            }

            _desc = ToString(); // Cache this; it may be called a lot when logging

            // Target:
            var      addr      = new C4Address();
            var      scheme    = new C4String();
            var      host      = new C4String();
            var      path      = new C4String();
            Database otherDB   = null;
            var      remoteUrl = Config.RemoteUrl;
            string   dbNameStr = null;

            if (remoteUrl != null)
            {
                var pathStr = String.Concat(remoteUrl.Segments.Take(remoteUrl.Segments.Length - 1));
                dbNameStr     = remoteUrl.Segments.Last().TrimEnd('/');
                scheme        = new C4String(remoteUrl.Scheme);
                host          = new C4String(remoteUrl.Host);
                path          = new C4String(pathStr);
                addr.scheme   = scheme.AsFLSlice();
                addr.hostname = host.AsFLSlice();
                addr.port     = (ushort)remoteUrl.Port;
                addr.path     = path.AsFLSlice();

                //get cookies from url and add to replicator options
                var cookiestring = Config.Database.GetCookies(remoteUrl);
                if (!String.IsNullOrEmpty(cookiestring))
                {
                    var split = cookiestring.Split(';') ?? Enumerable.Empty <string>();
                    foreach (var entry in split)
                    {
                        var pieces = entry?.Split('=');
                        if (pieces?.Length != 2)
                        {
                            WriteLog.To.Sync.W(Tag, "Garbage cookie value, ignoring");
                            continue;
                        }

                        Config.Options.Cookies.Add(new Cookie(pieces[0]?.Trim(), pieces[1]?.Trim()));
                    }
                }
            }
            else
            {
                Config.OtherDB?.CheckOpenLocked();
                otherDB = Config.OtherDB;
            }

            var options = Config.Options;

            Config.Authenticator?.Authenticate(options);

            options.Build();
            var push       = Config.ReplicatorType.HasFlag(ReplicatorType.Push);
            var pull       = Config.ReplicatorType.HasFlag(ReplicatorType.Pull);
            var continuous = Config.Continuous;

            var socketFactory = Config.SocketFactory;

            socketFactory.context = GCHandle.ToIntPtr(GCHandle.Alloc(this)).ToPointer();
            _nativeParams         = new ReplicatorParameters(options)
            {
                Push            = Mkmode(push, continuous),
                Pull            = Mkmode(pull, continuous),
                Context         = this,
                OnDocumentEnded = OnDocEnded,
                OnStatusChanged = StatusChangedCallback,
                SocketFactory   = &socketFactory
            };

            // Clear the reset flag, it is a one-time thing
            options.Reset = false;

            if (Config.PushFilter != null)
            {
                _nativeParams.PushFilter = PushFilterCallback;
            }
            if (Config.PullFilter != null)
            {
                _nativeParams.PullFilter = PullValidateCallback;
            }

            DispatchQueue.DispatchSync(() =>
            {
                C4Error localErr = new C4Error();
            #if COUCHBASE_ENTERPRISE
                if (otherDB != null)
                {
                    _repl = Native.c4repl_newLocal(Config.Database.c4db, otherDB.c4db, _nativeParams.C4Params,
                                                   &localErr);
                }
                else
            #endif
                _repl = Native.c4repl_new(Config.Database.c4db, addr, dbNameStr, _nativeParams.C4Params, &localErr);
                err   = localErr;
            });

            scheme.Dispose();
            path.Dispose();
            host.Dispose();

            return(err);
        }
		List<Activity> CreateActivityDataWithActivities (CMMotionActivity[] activities, Action completionHandler)
		{
			var results = new List<Activity> ();

			var group = DispatchGroup.Create ();
			var queue = new DispatchQueue ("resultQueue");

			var filteredActivities = activities.Where (activity => activity.HasActivitySignature ()
                 && !activity.Stationary
                 && activity.Confidence != CMMotionActivityConfidence.Low).ToArray<CMMotionActivity> ();

			var activitySegments = FindActivitySegments (filteredActivities);

			foreach (var segment in activitySegments) {
				group.Enter ();
				pedometer.QueryPedometerData (segment.Item1.StartDate, (NSDate)segment.Item2, (pedometerData, error) => {
					queue.DispatchAsync (() => {
						var activity = new Activity (segment.Item1,
			               ((DateTime)segment.Item1.StartDate).ToLocalTime (),
			               segment.Item2.ToLocalTime (),
			               pedometerData);
						
						results.Add (activity);
					});

					if (error != null)
						HandleError (error);

					group.Leave ();
				});
			}

			group.Notify (DispatchQueue.MainQueue, () => {
				queue.DispatchSync (() => {
					RecentActivities = results;
					RecentActivities.Reverse ();
					completionHandler?.Invoke ();
				});
			});

			return results;
		}