Exemplo n.º 1
0
 public void Alarm(AlarmEventArgs args)
 {
     MainThreadDispatcher.StartUpdateMicroCoroutine(AlarmLights(args.Duration));
 }
Exemplo n.º 2
0
 public void Christmas(ChristmasEventArgs args)
 {
     MainThreadDispatcher.StartUpdateMicroCoroutine(ChristLights(args.Duration, args.Nr));
 }
Exemplo n.º 3
0
    private void StartMain()
    {
        GameObject gm = new GameObject("FloorChanger");

        _manageFade = gm.AddComponent <ManageFade>();
        _manageFade.SetupFade();
        _manageFade.Wait = 0.01f;
        _manageFade.PlayFadeOut(false);

        GameObject.Find("OnBGMCheck").GetComponent <Toggle>().isOn =
            MusicInformation.Music.IsMusicOn;

        GameObject.Find("OnSoundCheck").GetComponent <Toggle>().isOn =
            SoundInformation.Sound.IsPlay;

        GameObject.Find("OnVoiceCheck").GetComponent <Toggle>().isOn =
            VoiceInformation.Voice.IsPlay;

        if (KeyControlInformation.Info.OpMode == OperationMode.UseMouse)
        {
            GameObject.Find("UseMouse").GetComponent <Toggle>().isOn =
                true;
        }

        if (ScoreInformation.Info.PlayerNameBase != CommonConst.Message.UnityChanName && ScoreInformation.Info.PlayerNameBase != CommonConst.Message.StellaChanName)
        {
            GameObject.Find("NameInputField").GetComponent <InputField>().text = ScoreInformation.Info.PlayerNameBase;
        }
        else
        {
            GameObject.Find("NameInputField").GetComponent <InputField>().text = "";
        }

        //MusicInformation.Music.Setup(MusicInformation.MusicType.CharacterSelect);

        ScrollViewSelected         = GameObject.Find("SelectTargetScrollView");
        ScrollViewSelectedUnit     = GameObject.Find("SelectUnit");
        ScrollViewSelectedContents = GameObject.Find("SelectTargetContent");

        _keyDisp = GameObject.Find("KeyDisplayPanel");

        CharacterStatusPanel = GameObject.Find("CharacterStatusPanel");
        DungeonStatusPanel   = GameObject.Find("DungeonStatusPanel");

        ScrollViewSelectedUnit.SetActive(false);
        DungeonStatusPanel.SetActive(false);

        SelectedList = new Dictionary <long, GameObject>();

        _state = SelectTurnState.ManageStart;

        _keyDisp.SetActive(false);


        //ダンジョンデータを読み込み
        Dungeons = TableDungeonMaster.GetAllValue();
        //キャラクターデータを読み込み
        Characters = TablePlayer.GetAllValue();
        //初期選択を格納
        SelectCharacter = Characters.First().Value.ObjNo;
        InitialzeContent(Characters, SelectCharacter);

        MainThreadDispatcher.StartUpdateMicroCoroutine(TransSceneStart(1f));
    }
Exemplo n.º 4
0
        public async Task RunAsync()
        {
            LoadingResult loadingResult = LoadingResult.Failed;
            bool          success       = false;

            try
            {
                if (IsCompleted || IsCancelled || ImageService.ExitTasksEarly)
                {
                    throw new OperationCanceledException();
                }

                ThrowIfCancellationRequested();

                // LOAD IMAGE
                if (!(await TryLoadFromMemoryCacheAsync().ConfigureAwait(false)))
                {
                    Logger.Debug(string.Format("Generating/retrieving image: {0}", Key));
                    var resolver = Parameters.CustomDataResolver ?? DataResolverFactory.GetResolver(Parameters.Path, Parameters.Source, Parameters, Configuration);
                    resolver = new WrappedDataResolver(resolver);
                    var imageData = await resolver.Resolve(Parameters.Path, Parameters, CancellationTokenSource.Token).ConfigureAwait(false);

                    loadingResult = imageData.Item2;

                    using (imageData.Item1)
                    {
                        ImageInformation = imageData.Item3;
                        ImageInformation.SetKey(Key, Parameters.CustomCacheKey);
                        ImageInformation.SetPath(Parameters.Path);
                        ThrowIfCancellationRequested();

                        // Preload
                        if (Parameters.Preload && Parameters.CacheType.HasValue && Parameters.CacheType.Value == CacheType.Disk)
                        {
                            if (loadingResult == LoadingResult.Internet)
                            {
                                Logger?.Debug(string.Format("DownloadOnly success: {0}", Key));
                            }

                            success = true;

                            return;
                        }

                        ThrowIfCancellationRequested();

                        var image = await GenerateImageAsync(Parameters.Path, Parameters.Source, imageData.Item1, imageData.Item3, true, false).ConfigureAwait(false);

                        ThrowIfCancellationRequested();

                        try
                        {
                            BeforeLoading(image, false);

                            if (image != default(TImageContainer) && CanUseMemoryCache)
                            {
                                MemoryCache.Add(Key, imageData.Item3, image);
                            }

                            ThrowIfCancellationRequested();

                            bool isFadeAnimationEnabled = Parameters.FadeAnimationEnabled ?? Configuration.FadeAnimationEnabled;
                            await SetTargetAsync(image, isFadeAnimationEnabled).ConfigureAwait(false);
                        }
                        finally
                        {
                            AfterLoading(image, false);
                        }
                    }
                }

                success = true;
            }
            catch (Exception ex)
            {
                if (ex is OperationCanceledException || ex is ObjectDisposedException)
                {
                    if (Configuration.VerboseLoadingCancelledLogging)
                    {
                        Logger.Debug(string.Format("Image loading cancelled: {0}", Key));
                    }
                }
                else
                {
                    if (_clearCacheOnOutOfMemory && ex is OutOfMemoryException)
                    {
                        MemoryCache.Clear();
                    }

                    Logger.Error(string.Format("Image loading failed: {0}", Key), ex);

                    if (Configuration.ExecuteCallbacksOnUIThread && Parameters?.OnError != null)
                    {
                        await MainThreadDispatcher.PostAsync(() =>
                        {
                            Parameters?.OnError?.Invoke(ex);
                        }).ConfigureAwait(false);
                    }
                    else
                    {
                        Parameters?.OnError?.Invoke(ex);
                    }

                    try
                    {
                        // Error placeholder if enabled
                        if (!Parameters.Preload && !string.IsNullOrWhiteSpace(Parameters.ErrorPlaceholderPath))
                        {
                            await ShowPlaceholder(Parameters.ErrorPlaceholderPath, KeyForErrorPlaceholder,
                                                  Parameters.ErrorPlaceholderSource, false).ConfigureAwait(false);
                        }
                    }
                    catch (Exception ex2)
                    {
                        if (!(ex2 is OperationCanceledException))
                        {
                            Logger.Error(string.Format("Image loading failed: {0}", Key), ex);
                        }
                    }
                }
            }
            finally
            {
                try
                {
                    if (CancellationTokenSource?.IsCancellationRequested == false)
                    {
                        CancellationTokenSource.Cancel();
                    }
                }
                catch (Exception)
                {
                }

                IsCompleted = true;

                using (Parameters)
                {
                    if (Configuration.ExecuteCallbacksOnUIThread && Parameters?.OnFinish != null)
                    {
                        await MainThreadDispatcher.PostAsync(() =>
                        {
                            if (success)
                            {
                                Parameters?.OnSuccess?.Invoke(ImageInformation, loadingResult);
                            }
                            Parameters?.OnFinish?.Invoke(this);
                        }).ConfigureAwait(false);
                    }
                    else
                    {
                        if (success)
                        {
                            Parameters?.OnSuccess?.Invoke(ImageInformation, loadingResult);
                        }
                        Parameters?.OnFinish?.Invoke(this);
                    }

                    ImageService.RemovePendingTask(this);
                }
            }
        }
Exemplo n.º 5
0
 /// <summary>
 /// start update AssetBundles
 /// </summary>
 public void StartUpdateAssetBundles()
 {
     MainThreadDispatcher.StartCoroutine(AssetBundlesUpdateStart());
 }
Exemplo n.º 6
0
        /// <summary>
        /// Loads the image from given stream asynchronously.
        /// </summary>
        /// <returns>An awaitable task.</returns>
        /// <param name="stream">The stream to get data from.</param>
        public override async Task <GenerateResult> LoadFromStreamAsync(Stream stream)
        {
            if (stream == null)
            {
                return(GenerateResult.Failed);
            }

            if (IsCancelled)
            {
                return(GenerateResult.Canceled);
            }

            WithLoadingResult <UIImage> resultWithImage;
            UIImage image = null;

            try
            {
                resultWithImage = await GetImageAsync("Stream", ImageSource.Stream, false, stream).ConfigureAwait(false);

                image = resultWithImage.Item;
            }
            catch (Exception ex)
            {
                Logger.Error("An error occured while retrieving image.", ex);
                resultWithImage = new WithLoadingResult <UIImage>(LoadingResult.Failed);
                image           = null;
            }

            if (image == null)
            {
                await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource, false).ConfigureAwait(false);

                return(resultWithImage.GenerateResult);
            }

            if (CanUseMemoryCache())
            {
                ImageCache.Instance.Add(GetKey(), resultWithImage.ImageInformation, image);
            }

            if (IsCancelled)
            {
                return(GenerateResult.Canceled);
            }

            if (_getNativeControl() == null)
            {
                return(GenerateResult.InvalidTarget);
            }

            try
            {
                // Post on main thread
                await MainThreadDispatcher.PostAsync(() =>
                {
                    if (IsCancelled)
                    {
                        return;
                    }

                    _doWithImage(image, true, false);
                    Completed = true;
                    Parameters?.OnSuccess(resultWithImage.ImageInformation, resultWithImage.Result);
                }).ConfigureAwait(false);

                if (!Completed)
                {
                    return(GenerateResult.Failed);
                }
            }
            catch (Exception ex2)
            {
                await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource, false).ConfigureAwait(false);

                throw ex2;
            }

            return(GenerateResult.Success);
        }
Exemplo n.º 7
0
        /// <summary>
        /// Tries to load requested image from the cache asynchronously.
        /// </summary>
        /// <returns>A boolean indicating if image was loaded from cache.</returns>
        private async Task <CacheResult> TryLoadingFromCacheAsync(ImageView imageView)
        {
            try
            {
                if (imageView == null)
                {
                    return(CacheResult.NotFound);                    // weird situation, dunno what to do
                }
                if (IsCancelled)
                {
                    return(CacheResult.NotFound);                    // not sure what to return in that case
                }
                var key = GetKey();

                if (string.IsNullOrWhiteSpace(key))
                {
                    return(CacheResult.NotFound);
                }

                var value = ImageCache.Instance.Get(key);
                if (value == null)
                {
                    return(CacheResult.NotFound);                    // not available in the cache
                }
                if (IsCancelled)
                {
                    return(CacheResult.NotFound);                    // not sure what to return in that case
                }
                Logger.Debug(string.Format("Image from cache: {0}", key));
                await MainThreadDispatcher.PostAsync(() =>
                {
                    if (IsCancelled)
                    {
                        return;
                    }

                    var ffDrawable = value as FFBitmapDrawable;
                    if (ffDrawable != null)
                    {
                        ffDrawable.StopFadeAnimation();
                    }

                    imageView.SetImageDrawable(value);
                    if (Utils.HasJellyBean() && imageView.AdjustViewBounds)
                    {
                        imageView.LayoutParameters.Height = value.IntrinsicHeight;
                        imageView.LayoutParameters.Width  = value.IntrinsicWidth;
                    }
                }).ConfigureAwait(false);

                if (IsCancelled)
                {
                    return(CacheResult.NotFound);                    // not sure what to return in that case
                }
                if (Parameters.OnSuccess != null)
                {
                    Parameters.OnSuccess(value.IntrinsicWidth, value.IntrinsicHeight);
                }
                return(CacheResult.Found);                // found and loaded from cache
            }
            catch (Exception ex)
            {
                if (Parameters.OnError != null)
                {
                    Parameters.OnError(ex);
                }
                return(CacheResult.ErrorOccured);                // weird, what can we do if loading from cache fails
            }
        }
Exemplo n.º 8
0
 public Core(IObserver <float> observer)
 {
     _observer = observer;
     MainThreadDispatcher.StartUpdateMicroCoroutine(Worker());
 }
Exemplo n.º 9
0
            private void ReceiveCallback(IAsyncResult result)
            {
                try
                {
                    ReceiveState state = (ReceiveState)result.AsyncState;
                    SocketError  socketError;

                    //int byteLength = stream.EndRead(result);
                    int byteLength = socket.EndReceive(result, out socketError);
                    int dataOffset = 0;

                    if (socketError != SocketError.Success)
                    {
                        Debug.LogError($"Socket Error:{socketError}");
                        client.Disconnect();
                        return;
                    }

                    if (byteLength <= 0)
                    {
                        client.Disconnect();
                        return;
                    }

                    if (!state.DataSizeReceived)
                    {
                        if (byteLength >= 4)
                        {
                            state.DataSize = BitConverter.ToInt32(state.Buffer, 0);
                            //Debug.Log($"Received Data: {state.DataSize}");
                            state.DataSizeReceived = true;
                            byteLength            -= 4;
                            dataOffset            += 4;
                        }
                    }

                    if ((state.Data.Length + byteLength) == state.DataSize)
                    {
                        state.Data.Write(state.Buffer, dataOffset, byteLength);

                        Packet       packet   = state.Data.ToArray().Deserialize <Packet>();
                        ReceiveState newState = new ReceiveState();

                        if (!string.IsNullOrEmpty(packet.MethodName))
                        {
                            MainThreadDispatcher.AddMessage(packet);
                        }
                        else
                        {
                            Debug.LogError($"Cant have a null method name in packet!");
                        }

                        socket.BeginReceive(newState.Buffer, 0, dataBufferSize, SocketFlags.None, ReceiveCallback, newState);

                        //byte[] data = new byte[byteLength];
                        //Array.Copy(receiveBuffer, data, byteLength);
                        //Debug.Log($"Recieved Some Data {data.Length}");
                        //MainThreadDispatcher.AddMessage(data.Deserialize<Packet>());
                        //stream.BeginRead(receiveBuffer, 0, dataBufferSize, ReceiveCallback, null);
                        //socket.BeginReceive(receiveBuffer, 0, dataBufferSize, SocketFlags.None, ReceiveCallback, null);
                    }
                    else
                    {
                        //Debug.LogError($"Has not yet received all the data, waiting for more to come in");
                        state.Data.Write(state.Buffer, dataOffset, byteLength);
                        socket.BeginReceive(state.Buffer, 0, state.Buffer.Length, SocketFlags.None, new AsyncCallback(ReceiveCallback), state);
                    }
                }
                catch (Exception e)
                {
                    Debug.LogError(e.Message);
                    Disconnect();
                }
            }
Exemplo n.º 10
0
        /// <summary>
        /// Runs the image loading task: gets image from file, url, asset or cache. Then assign it to the imageView.
        /// </summary>
        protected override async Task <GenerateResult> TryGeneratingImageAsync()
        {
            BitmapDrawable drawable = null;

            if (!string.IsNullOrWhiteSpace(Parameters.Path))
            {
                try
                {
                    drawable = await RetrieveDrawableAsync(Parameters.Path, Parameters.Source, false).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Logger.Error("An error occured while retrieving drawable.", ex);
                    drawable = null;
                }
            }

            var imageView = GetAttachedImageView();

            if (imageView == null)
            {
                return(GenerateResult.InvalidTarget);
            }

            if (drawable == null)
            {
                // Show error placeholder
                await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource, imageView, false).ConfigureAwait(false);

                return(GenerateResult.Failed);
            }

            Exception trappedException = null;

            try
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    return(GenerateResult.Canceled);
                }

                // Post on main thread
                await MainThreadDispatcher.PostAsync(() =>
                {
                    if (CancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    SetImageDrawable(imageView, drawable, UseFadeInBitmap);
                    Completed = true;
                    Parameters.OnSuccess(drawable.IntrinsicWidth, drawable.IntrinsicHeight);
                }).ConfigureAwait(false);

                if (!Completed)
                {
                    return(GenerateResult.Failed);
                }
            }
            catch (Exception ex2)
            {
                trappedException = ex2;                 // All this stupid stuff is necessary to compile with c# 5, since we can't await in a catch block...
            }

            // All this stupid stuff is necessary to compile with c# 5, since we can't await in a catch block...
            if (trappedException != null)
            {
                // Show error placeholder
                await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource, imageView, false).ConfigureAwait(false);

                throw trappedException;
            }

            return(GenerateResult.Success);
        }
        protected async override Task SetTargetAsync(SelfDisposingBitmapDrawable image, bool animated)
        {
            if (Target == null)
            {
                return;
            }

            ThrowIfCancellationRequested();

            if (image is FFBitmapDrawable ffDrawable)
            {
                if (ffDrawable.IsAnimationRunning)
                {
                    var mut = new FFBitmapDrawable(Context.Resources, ffDrawable.Bitmap, ffDrawable);
                    ffDrawable = mut as FFBitmapDrawable;
                    image      = ffDrawable;

                    // old hacky workaround
                    //await Task.Delay(ffDrawable.FadeDuration + 50).ConfigureAwait(false);
                }

                if (animated)
                {
                    SelfDisposingBitmapDrawable placeholderDrawable = null;
                    PlaceholderWeakReference?.TryGetTarget(out placeholderDrawable);

                    if (placeholderDrawable == null)
                    {
                        // Enable fade animation when no placeholder is set and the previous image is not null
                        var imageView = PlatformTarget.Control as ImageViewAsync;
                        placeholderDrawable = imageView?.Drawable as SelfDisposingBitmapDrawable;
                    }

                    var fadeDuration = Parameters.FadeAnimationDuration ?? Configuration.FadeAnimationDuration;

                    if (placeholderDrawable.IsValidAndHasValidBitmap())
                    {
                        placeholderDrawable?.SetIsRetained(true);
                        ffDrawable?.SetPlaceholder(placeholderDrawable, fadeDuration);
                        placeholderDrawable?.SetIsRetained(false);
                    }
                    else if (ffDrawable.IsValidAndHasValidBitmap())
                    {
                        var width  = ffDrawable.Bitmap.Width;
                        var height = ffDrawable.Bitmap.Height;
                        var bitmap = Bitmap.CreateBitmap(width, height, Bitmap.Config.Argb8888);

                        using (var canvas = new Canvas(bitmap))
                            using (var paint = new Paint()
                            {
                                Color = _placeholderHelperColor
                            })
                            {
                                canvas.DrawRect(0, 0, width, height, paint);
                            }

                        ffDrawable?.SetPlaceholder(new SelfDisposingBitmapDrawable(Context.Resources, bitmap), fadeDuration);
                    }
                }
                else
                {
                    ffDrawable?.SetPlaceholder(null, 0);
                }
            }

            await MainThreadDispatcher.PostAsync(() =>
            {
                ThrowIfCancellationRequested();

                PlatformTarget.Set(this, image, animated);
            }).ConfigureAwait(false);
        }
Exemplo n.º 12
0
        /// <summary>
        /// Runs the image loading task: gets image from file, url, asset or cache. Then assign it to the imageView.
        /// </summary>
        protected override async Task <GenerateResult> TryGeneratingImageAsync()
        {
            WithLoadingResult <UIImage> imageWithResult = null;
            UIImage image = null;

            try
            {
                imageWithResult = await RetrieveImageAsync(Parameters.Path, Parameters.Source, false).ConfigureAwait(false);

                image = imageWithResult == null ? null : imageWithResult.Item;
            }
            catch (Exception ex)
            {
                Logger.Error("An error occured while retrieving image.", ex);
                image = null;
            }

            if (image == null)
            {
                await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource).ConfigureAwait(false);

                return(GenerateResult.Failed);
            }

            if (CancellationToken.IsCancellationRequested)
            {
                return(GenerateResult.Canceled);
            }

            if (_getNativeControl() == null)
            {
                return(GenerateResult.InvalidTarget);
            }

            try
            {
                // Post on main thread
                await MainThreadDispatcher.PostAsync(() =>
                {
                    if (CancellationToken.IsCancellationRequested)
                    {
                        return;
                    }

                    _doWithImage(image, false);
                    Completed = true;
                    Parameters.OnSuccess(new ImageSize((int)image.Size.Width, (int)image.Size.Height), imageWithResult.Result);
                }).ConfigureAwait(false);

                if (!Completed)
                {
                    return(GenerateResult.Failed);
                }
            }
            catch (Exception ex2)
            {
                await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource).ConfigureAwait(false);

                throw ex2;
            }

            return(GenerateResult.Success);
        }
Exemplo n.º 13
0
 /// <summary>
 /// Allows you to dispatch an delegate returning an object (for example: a newly instantiated gameobject) that is directly available in your ThreadPool-Thread.
 /// Because the thread you are dispatching from is not the MainThread, your ThreadPool-thread needs to wait till the MainThread executed the method, and the returned value can be used directly
 /// </summary>
 /// <param name="dispatchCall">Example: "(object obj) => Debug.Log("This will be fired from the MainThread: " + System.Threading.Thread.CurrentThread.Name + "\nObject: " + obj.toString())"</param>
 /// <param name="safeMode">Executes all the computations within try-catch events, logging it the message + stacktrace</param>
 /// <returns>After the MainThread has executed the "dispatchCall" (and the worker-thread has been waiting), it will return whatever the dispatchCall returns to the worker-thread</returns>
 public static object DispatchToMainThreadReturn(ThreadDispatchDelegateReturn dispatchCall, bool safeMode = true)
 {
     return(MainThreadDispatcher.DispatchToMainThreadReturn(dispatchCall, safeMode));
 }
Exemplo n.º 14
0
 /// <summary>
 /// When executed by the MainThread, this argument will be passed to the "dispatchCall";
 /// Allows you to dispatch an delegate returning an object (for example: a newly instantiated gameobject) that is directly available in your ThreadPool-Thread.
 /// Because the thread you are dispatching from is not the MainThread, your ThreadPool-thread needs to wait till the MainThread executed the method, and the returned value can be used directly
 /// </summary>
 /// <param name="dispatchCall">Example: "(object obj) => Debug.Log("This will be fired from the MainThread: " + System.Threading.Thread.CurrentThread.Name + "\nObject: " + obj.toString())"</param>
 /// <param name="dispatchArgument">Once the MainThread executes this action, the argument will be passed to the delegate</param>
 /// <param name="safeMode">Executes all the computations within try-catch events, logging it the message + stacktrace</param>
 /// <returns>After the MainThread has executed the "dispatchCall" (and the worker-thread has been waiting), it will return whatever the dispatchCall returns to the worker-thread</returns>
 public static object DispatchToMainThreadReturn(ThreadDispatchDelegateArgReturn dispatchCall, object dispatchArgument, bool safeMode = true)
 {
     return(MainThreadDispatcher.DispatchToMainThreadReturn(dispatchCall, dispatchArgument, safeMode));
 }
Exemplo n.º 15
0
        /// <summary>
        /// Loads given placeHolder into the imageView.
        /// </summary>
        /// <returns>An awaitable task.</returns>
        /// <param name="placeholderPath">Full path to the placeholder.</param>
        /// <param name="source">Source for the path: local, web, assets</param>
        protected async Task <bool> LoadPlaceHolderAsync(string placeholderPath, ImageSource source, ImageView imageView, bool isLoadingPlaceholder)
        {
            if (string.IsNullOrWhiteSpace(placeholderPath))
            {
                return(false);
            }

            if (imageView == null)
            {
                return(false);
            }

            BitmapDrawable drawable = ImageCache.Instance.Get(GetKey(placeholderPath));

            if (drawable != null)
            {
                // We should wrap drawable in an AsyncDrawable, nothing is deferred
                drawable = new AsyncDrawable(Context.Resources, drawable.Bitmap, this);
            }
            else
            {
                // Here we asynchronously load our placeholder: it is deferred so we need a temporary AsyncDrawable
                drawable = new AsyncDrawable(Context.Resources, null, this);
                await MainThreadDispatcher.PostAsync(() =>
                {
                    imageView.SetImageDrawable(drawable);                     // temporary assign this AsyncDrawable
                }).ConfigureAwait(false);

                try
                {
                    drawable = await RetrieveDrawableAsync(placeholderPath, source, isLoadingPlaceholder).ConfigureAwait(false);
                }
                catch (Exception ex)
                {
                    Logger.Error("An error occured while retrieving drawable.", ex);
                    return(false);
                }
            }

            if (drawable == null)
            {
                return(false);
            }

            _loadingPlaceholderWeakReference = new WeakReference <Drawable>(drawable);

            if (CancellationToken.IsCancellationRequested)
            {
                return(false);
            }

            await MainThreadDispatcher.PostAsync(() =>
            {
                if (CancellationToken.IsCancellationRequested)
                {
                    return;
                }

                SetImageDrawable(imageView, drawable, false);
            }).ConfigureAwait(false);

            return(true);
        }
Exemplo n.º 16
0
        public override void Initialize()
        {
            ResetStatus();

            MainThreadDispatcher.StartUpdateMicroCoroutine(UpdateEnumerator());
        }
Exemplo n.º 17
0
 /// <summary>
 /// Spawns the startup actions.
 /// </summary>
 private void SpawnStartupActions()
 {
     MainThreadDispatcher.BeginInvoke(new System.Action(() => ExecuteStartupActions()));
 }
Exemplo n.º 18
0
    private IDisposable BindPlot2PLC(int lane)
    {
        switch (lane)
        {
        case 0:
            return
                (_inputModule
                 .P1Data
                 .Subscribe(x =>
            {
                MainThreadDispatcher.Post(_ =>
                {
                    var pos = new Vector2(GameManager.ManualInputAllowed_External?x[1]:x[1].FromTo(0, 960, 960, 0), x[2]);
                    Debug.Log("Lane 1 " + pos);
                    PlottingPoint.anchoredPosition = pos;
                }, null);
            }));

        case 1:
            return
                (_inputModule
                 .P2Data
                 .Subscribe(x =>
            {
                MainThreadDispatcher.Post(_ =>
                {
                    var pos = new Vector2(GameManager.ManualInputAllowed_External?x[1]:x[1].FromTo(0, 960, 960, 0), x[2]);
                    if (Verbose)
                    {
                        Debug.Log("Lane 2 " + pos);
                    }
                    PlottingPoint.anchoredPosition = pos;
                }, null);
            }));

        case 2:
            return
                (_inputModule
                 .P3Data
                 .Subscribe(x =>
            {
                MainThreadDispatcher.Post(_ =>
                {
                    var pos = new Vector2(GameManager.ManualInputAllowed_External?x[1]:x[1].FromTo(0, 960, 960, 0), x[2]);

                    if (Verbose)
                    {
                        Debug.Log("Lane 3 " + pos);
                    }
                    PlottingPoint.anchoredPosition = pos;
                }, null);
            }));

        default:
            return
                (_inputModule
                 .P4Data
                 .Subscribe(x =>
            {
                MainThreadDispatcher.Post(_ =>
                {
                    var pos = new Vector2(GameManager.ManualInputAllowed_External?x[1]:x[1].FromTo(0, 960, 960, 0), x[2]);
                    if (Verbose)
                    {
                        Debug.Log("Lane 4 " + pos);
                    }
                    PlottingPoint.anchoredPosition = pos;
                }, null);
            }));
        }
    }
Exemplo n.º 19
0
 public static void RunOnUiThread(this object obj, Action action)
 {
     MainThreadDispatcher.Post(action);
 }
Exemplo n.º 20
0
        IEnumerator UpdateAssetBundle(string assetBundleServerPath, string assetBundleLocalPath)
        {
            string localAssetBundleManifestPath  = $"{assetBundleLocalPath}/{AssetBundlePathResolver.Instance.BundleSaveDirName}";
            string serverAssetBundleManifestPath = $"{assetBundleServerPath}/{AssetBundlePathResolver.Instance.BundleSaveDirName}";

            string localDependFilePath  = $"{assetBundleLocalPath}/{AssetBundlePathResolver.Instance.DependFileName}";
            string serverDependFilePath = $"{assetBundleServerPath}/{AssetBundlePathResolver.Instance.DependFileName}";

            AssetBundleManifest localAssetBundleManifest  = null;
            AssetBundleManifest serverAssetBundleManifest = null;

            if (FileUtility.CheckFileIsExist(localAssetBundleManifestPath) == false)
            {
                yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverAssetBundleManifestPath, localAssetBundleManifestPath)));

                if (m_HasError)
                {
                    deleteFolder = true;
                    yield break;
                }

                yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverDependFilePath, localDependFilePath)));

                if (m_HasError)
                {
                    deleteFolder = true;
                    yield break;
                }

                localAssetBundleManifest           = LoadLocalAssetBundleManifest(localAssetBundleManifestPath);
                m_NeedDownloadAssetBundleNamesList = localAssetBundleManifest.GetAllAssetBundles().ToList();
                int currentCount = 0;
                for (int i = 0; i < m_NeedDownloadAssetBundleNamesList.Count; i++)
                {
                    string assetBundleName = m_NeedDownloadAssetBundleNamesList[i];

                    string serverAssetBundlesPath = string.Format("{0}/{1}", assetBundleServerPath, assetBundleName);

                    string localAssetBundlesPath = string.Format("{0}/{1}", assetBundleLocalPath, assetBundleName);

                    yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverAssetBundlesPath, localAssetBundlesPath)));

                    if (m_HasError)
                    {
                        deleteFolder = true;
                        yield break;
                    }

                    currentCount++;
                    AssetBundleUpdateProcessEvent?.Invoke((float)currentCount / m_NeedDownloadAssetBundleNamesList.Count);
                }
            }
            else
            {
                byte[] localAssetBundleManifestBytes = FileUtility.FileConvertToBytes(localAssetBundleManifestPath);
                //load AssetBundleManifest to memory from server
                WWW serverWWW = new WWW(serverAssetBundleManifestPath);

                yield return(serverWWW);

                if (serverWWW.error != null)
                {
                    m_HasError = true;
                    yield break;
                }

                byte[] serverAssetBundleManifestBytes = serverWWW.bytes;
                serverWWW.Dispose();

                if (HashUtil.Get(localAssetBundleManifestBytes) == HashUtil.Get(serverAssetBundleManifestBytes))
                {
                    AssetBundleUpdateProcessEvent?.Invoke(1);
                    yield break;
                }

                yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverDependFilePath, localDependFilePath)));

                if (m_HasError)
                {
                    deleteFolder = true;
                    yield break;
                }

                serverAssetBundleManifest = LoadAssetBundleManifest(serverAssetBundleManifestBytes);
                localAssetBundleManifest  = LoadLocalAssetBundleManifest(localAssetBundleManifestPath);

                string[] localAssetBundleNames  = localAssetBundleManifest.GetAllAssetBundles();
                string[] serverAssetBundleNames = serverAssetBundleManifest.GetAllAssetBundles();

                ///Check each AssetBundles from server
                for (int i = 0; i < serverAssetBundleNames.Length; i++)
                {
                    string assetBundleName = serverAssetBundleNames[i];

                    if (localAssetBundleNames.Contains(assetBundleName))
                    {
                        Hash128 localAssetBundleHash = localAssetBundleManifest.GetAssetBundleHash(assetBundleName);

                        Hash128 serverAssetBundleHash = serverAssetBundleManifest.GetAssetBundleHash(assetBundleName);

                        //if the hash value is different,delete the AssetBundle file in local machine,then download the AssetBundle from server
                        if (localAssetBundleHash != serverAssetBundleHash)
                        {
                            m_NeedDownloadAssetBundleNamesList.Add(assetBundleName);
                        }
                    }
                    else
                    {
                        m_NeedDownloadAssetBundleNamesList.Add(assetBundleName);
                    }
                }

                //delete redundant AssetBundles in local machine
                for (int i = 0; i < localAssetBundleNames.Length; i++)
                {
                    string assetBundleName = localAssetBundleNames[i];

                    if (!serverAssetBundleNames.Contains(assetBundleName))
                    {
                        string deleteAssetBundlePath = string.Format("{0}/{1}", assetBundleLocalPath, assetBundleName);

                        //delete redundant AssetBundles
                        FileUtility.DeleteFile(deleteAssetBundlePath);
                        FileUtility.IfDeletedFileCurrentDirectoryIsEmptyDeleteRecursively(deleteAssetBundlePath);
                    }
                }
                int currentCount = 0;
                for (int i = 0; i < m_NeedDownloadAssetBundleNamesList.Count; i++)
                {
                    string assetBundleName = m_NeedDownloadAssetBundleNamesList[i];

                    string serverAssetBundlesPath = string.Format("{0}/{1}", assetBundleServerPath, assetBundleName);

                    string localAssetBundlesPath = string.Format("{0}/{1}", assetBundleLocalPath, assetBundleName);

                    yield return(MainThreadDispatcher.StartCoroutine(DownLoadAssetBundle(serverAssetBundlesPath, localAssetBundlesPath)));

                    if (m_HasError)
                    {
                        deleteFolder = true;
                        yield break;
                    }

                    currentCount++;
                    AssetBundleUpdateProcessEvent?.Invoke((float)currentCount / m_NeedDownloadAssetBundleNamesList.Count);
                }

                FileUtility.BytesConvertToFile(serverAssetBundleManifestBytes, localAssetBundleManifestPath);
            }
            AssetBundleUpdateProcessEvent?.Invoke(1);
            serverAssetBundleManifest = null;
            localAssetBundleManifest  = null;
            Resources.UnloadUnusedAssets();
        }
Exemplo n.º 21
0
 public static void RunOnUiThread(this object obj, Action action, long delayMillis)
 {
     MainThreadDispatcher.PostAsyc(action, delayMillis);
 }
Exemplo n.º 22
0
        /// <summary>
        /// Runs the image loading task: gets image from file, url, asset or cache. Then assign it to the imageView.
        /// </summary>
        protected override async Task <GenerateResult> TryGeneratingImageAsync()
        {
            WithLoadingResult <UIImage> imageWithResult;
            UIImage image = null;

            try
            {
                imageWithResult = await RetrieveImageAsync(Parameters.Path, Parameters.Source, false).ConfigureAwait(false);

                image = imageWithResult.Item;
            }
            catch (Exception ex)
            {
                Logger.Error("An error occured while retrieving image.", ex);
                imageWithResult = new WithLoadingResult <UIImage>(LoadingResult.Failed);
                image           = null;
            }

            if (image == null)
            {
                await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource, true).ConfigureAwait(false);

                return(imageWithResult.GenerateResult);
            }

            if (IsCancelled)
            {
                return(GenerateResult.Canceled);
            }

            if (_getNativeControl() == null)
            {
                return(GenerateResult.InvalidTarget);
            }

            try
            {
                // Post on main thread
                await MainThreadDispatcher.PostAsync(() =>
                {
                    if (IsCancelled)
                    {
                        return;
                    }

                    _doWithImage(image, imageWithResult.Result.IsLocalOrCachedResult(), false);
                    Completed = true;
                    Parameters?.OnSuccess(imageWithResult.ImageInformation, imageWithResult.Result);
                }).ConfigureAwait(false);

                if (!Completed)
                {
                    return(GenerateResult.Failed);
                }
            }
            catch (Exception ex2)
            {
                await LoadPlaceHolderAsync(Parameters.ErrorPlaceholderPath, Parameters.ErrorPlaceholderSource, false).ConfigureAwait(false);

                throw ex2;
            }

            return(GenerateResult.Success);
        }
Exemplo n.º 23
0
 private void Prov_FftCalculated(object sender, Providers.SampleAggregator.FftEventArgs e)
 {
     MainThreadDispatcher.BeginInvoke(new Action(() => { UpdateRes(e.Result); }));
 }
Exemplo n.º 24
0
        public async virtual Task <bool> TryLoadFromMemoryCacheAsync()
        {
            try
            {
                if (Parameters.Preload && Parameters.CacheType.HasValue && Parameters.CacheType.Value == CacheType.Disk)
                {
                    return(false);
                }

                bool isFadeAnimationEnabledForCached = Parameters.FadeAnimationForCachedImagesEnabled.HasValue ? Parameters.FadeAnimationForCachedImagesEnabled.Value : Configuration.FadeAnimationForCachedImages;
                var  result = await TryLoadFromMemoryCacheAsync(Key, true, isFadeAnimationEnabledForCached, false).ConfigureAwait(false);

                if (result)
                {
                    Logger.Debug(string.Format("Image loaded from cache: {0}", Key));
                    IsCompleted = true;

                    if (Configuration.ExecuteCallbacksOnUIThread && (Parameters?.OnSuccess != null || Parameters?.OnFinish != null))
                    {
                        await MainThreadDispatcher.PostAsync(() =>
                        {
                            Parameters?.OnSuccess?.Invoke(ImageInformation, LoadingResult.MemoryCache);
                            Parameters?.OnFinish?.Invoke(this);
                        }).ConfigureAwait(false);
                    }
                    else
                    {
                        Parameters?.OnSuccess?.Invoke(ImageInformation, LoadingResult.MemoryCache);
                        Parameters?.OnFinish?.Invoke(this);
                    }
                }
                else
                {
                    ThrowIfCancellationRequested();
                    // Loading placeholder if enabled
                    if (!_isLoadingPlaceholderLoaded && !string.IsNullOrWhiteSpace(Parameters.LoadingPlaceholderPath))
                    {
                        await ShowPlaceholder(Parameters.LoadingPlaceholderPath, KeyForLoadingPlaceholder,
                                              Parameters.LoadingPlaceholderSource, true).ConfigureAwait(false);
                    }
                }

                return(result);
            }
            catch (Exception ex)
            {
                if (_clearCacheOnOutOfMemory && ex is OutOfMemoryException)
                {
                    MemoryCache.Clear();
                }

                if (ex is OperationCanceledException)
                {
                    if (Configuration.VerboseLoadingCancelledLogging)
                    {
                        Logger.Debug(string.Format("Image loading cancelled: {0}", Key));
                    }
                }
                else
                {
                    Logger.Error(string.Format("Image loading failed: {0}", Key), ex);

                    if (Configuration.ExecuteCallbacksOnUIThread && Parameters?.OnError != null)
                    {
                        await MainThreadDispatcher.PostAsync(() =>
                        {
                            Parameters?.OnError?.Invoke(ex);
                        }).ConfigureAwait(false);
                    }
                    else
                    {
                        Parameters?.OnError?.Invoke(ex);
                    }
                }
            }

            return(false);
        }
Exemplo n.º 25
0
        //--------------- Private Session Variables --------------------



        //--------------------------------------- UNITY MONOBEHAVIOUR COMMANDS --------------------------------------
        //--------------------------------------- UNITY MONOBEHAVIOUR COMMANDS --------------------------------------
        #region UNITY MONOBEHAVIOUR COMMANDS

        protected virtual void Awake()
        {
            MainThreadWatchdog.Init();
            MainThreadDispatcher.Init();
            UnityActivityWatchdog.Init();
        }
Exemplo n.º 26
0
 // Use this for initialization
 void Start()
 {
     MainThreadDispatcher.Initialize();
 }
Exemplo n.º 27
0
            private void RecursiveRun(Action self)
            {
                object obj = this.gate;

                lock (obj)
                {
                    this.nextSelf = self;
                    if (!this.isDisposed)
                    {
                        if (!this.isStopped)
                        {
                            bool      flag = false;
                            Exception ex   = null;
                            try
                            {
                                flag = this.e.MoveNext();
                                if (flag)
                                {
                                    if (this.e.Current == null)
                                    {
                                        throw new InvalidOperationException("sequence is null.");
                                    }
                                }
                                else
                                {
                                    this.e.Dispose();
                                }
                            }
                            catch (Exception ex2)
                            {
                                ex = ex2;
                                this.e.Dispose();
                            }
                            if (ex != null)
                            {
                                this.stopper.Dispose();
                                this.observer.OnError(ex);
                            }
                            else if (!flag)
                            {
                                this.stopper.Dispose();
                                this.observer.OnCompleted();
                            }
                            else
                            {
                                IObservable <T>            observable = this.e.Current;
                                SingleAssignmentDisposable singleAssignmentDisposable = new SingleAssignmentDisposable();
                                this.subscription.Disposable = singleAssignmentDisposable;
                                if (this.isFirstSubscribe)
                                {
                                    this.isFirstSubscribe = false;
                                    singleAssignmentDisposable.Disposable = observable.Subscribe(this);
                                }
                                else
                                {
                                    MainThreadDispatcher.SendStartCoroutine(RepeatUntilObservable <T> .RepeatUntil.SubscribeAfterEndOfFrame(singleAssignmentDisposable, observable, this, this.parent.lifeTimeChecker));
                                }
                            }
                        }
                    }
                }
            }
Exemplo n.º 28
0
 public void Flicker(FlickerEventArgs args)
 {
     MainThreadDispatcher.StartUpdateMicroCoroutine(FlickerLights(args.OfTime, args.OnTime));
 }
Exemplo n.º 29
0
 public void StopCoroutine(Coroutine coroutine)
 {
     _coroutines.Remove(coroutine);
     MainThreadDispatcher.StopCoroutine(coroutine);
 }
Exemplo n.º 30
0
 private void RegisterApplicationQuitEvent(object a)
 {
     MainThreadDispatcher.OnApplicationQuitAsObservable().Subscribe(_ => Debug.Log("OnApplicationQuitAsObservable"));
 }
 public MainThreadMarshaller(MainThreadDispatcher dispatcher)
 {
     this.dispatcher = dispatcher;
 }