public DelayedFileSearchService(Dispatcher dispatcher, IFileSearchService innerService)
 {
     Ensure.NotNull(dispatcher, "dispatcher");
     Ensure.NotNull(innerService, "innerService");
     this.dispatcher = new DispatcherHelper(dispatcher);
     this.innerService = innerService;
 }
 /// <summary>
 /// Creates new instance.
 /// </summary>
 /// <param name="dispatcher">A threading helper.</param>
 /// <param name="action">An action to execute.</param>
 /// <param name="delay">A delay to kill requests between.</param>
 public ThrottlingHelper(DispatcherHelper dispatcher, Action action, int delay = 100)
 {
     Ensure.NotNull(dispatcher, "dispatcher");
     Ensure.NotNull(action, "action");
     Ensure.PositiveOrZero(delay, "delay");
     this.dispatcher = dispatcher;
     this.action = action;
     this.delay = delay;
 }
        private void PrepareStartup(StartupEventArgs e)
        {
            DispatcherHelper = new DispatcherHelper(Dispatcher);

            StartupModelProvider provider = new StartupModelProvider();
            startup = provider.Get(e.Args);
            startup.IsStartup = true;

            if (!startup.IsHidden)
                startup.IsHidden = Settings.Default.IsHiddentOnStartup;
        }
Esempio n. 4
0
        /// <summary>
        /// </summary>
        /// <param name="statusEntriesPlayers"></param>
        private void ProcessHealingOverTime(IEnumerable <StatusEntry> statusEntriesPlayers)
        {
            foreach (var statusEntry in statusEntriesPlayers)
            {
                try
                {
                    var statusInfo = StatusEffectHelper.StatusInfo(statusEntry.StatusID);
                    var statusKey  = "";
                    switch (Constants.GameLanguage)
                    {
                    case "English":
                        statusKey = statusInfo.Name.English;
                        break;

                    case "French":
                        statusKey = statusInfo.Name.French;
                        break;

                    case "German":
                        statusKey = statusInfo.Name.German;
                        break;

                    case "Japanese":
                        statusKey = statusInfo.Name.Japanese;
                        break;
                    }
                    if (String.IsNullOrWhiteSpace(statusKey))
                    {
                        continue;
                    }
                    var             amount     = NPCEntry.Level / ((60 - NPCEntry.Level) * .025m);
                    var             key        = statusKey;
                    XOverTimeAction actionData = null;
                    foreach (var healingOverTimeAction in HealingOverTimeHelper.PlayerActions.ToList()
                             .Where(d => String.Equals(d.Key, key, Constants.InvariantComparer)))
                    {
                        actionData = healingOverTimeAction.Value;
                    }
                    if (actionData == null)
                    {
                        continue;
                    }
                    var zeroFoundInList    = false;
                    var regen              = Regex.IsMatch(key, @"(リジェネ|récup|regen|whispering|murmure|erhebendes|光の囁き)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
                    var healingHistoryList = ParseHelper.LastAmountByAction.GetPlayer(Name)
                                             .ToList();
                    var resolvedPotency = 350;
                    foreach (var healingAction in healingHistoryList)
                    {
                        if (regen)
                        {
                            var found         = false;
                            var cureActions   = HealingOverTimeHelper.CureActions;
                            var medicaActions = HealingOverTimeHelper.MedicaActions;
                            var action        = healingAction;
                            if (cureActions["III"].Any(cureAction => String.Equals(action.Key, cureAction, Constants.InvariantComparer)))
                            {
                                found           = zeroFoundInList = true;
                                resolvedPotency = 550;
                            }
                            if (cureActions["II"].Any(cureAction => String.Equals(action.Key, cureAction, Constants.InvariantComparer)))
                            {
                                found           = zeroFoundInList = true;
                                resolvedPotency = 650;
                            }
                            if (cureActions["I"].Any(cureAction => String.Equals(action.Key, cureAction, Constants.InvariantComparer)))
                            {
                                found           = zeroFoundInList = true;
                                resolvedPotency = 400;
                            }
                            if (medicaActions["II"].Any(medicaAction => String.Equals(action.Key, medicaAction, Constants.InvariantComparer)))
                            {
                                found           = zeroFoundInList = true;
                                resolvedPotency = 200;
                            }
                            if (medicaActions["I"].Any(medicaAction => String.Equals(action.Key, medicaAction, Constants.InvariantComparer)))
                            {
                                found           = zeroFoundInList = true;
                                resolvedPotency = 300;
                            }
                            if (found)
                            {
                                if (action.Value > 0)
                                {
                                    amount = action.Value;
                                }
                                break;
                            }
                        }
                        if (String.Equals(healingAction.Key, key, Constants.InvariantComparer))
                        {
                            amount = healingAction.Value;
                            break;
                        }
                    }
                    statusKey = String.Format("{0} [•]", statusKey);
                    if (amount == 0)
                    {
                        amount = 75;
                    }
                    resolvedPotency = zeroFoundInList ? resolvedPotency : regen ? resolvedPotency : actionData.ActionPotency;
                    var tickHealing = Math.Ceiling(((amount / resolvedPotency) * actionData.ActionOverTimePotency) / 3);
                    if (actionData.HasNoInitialResult && !zeroFoundInList)
                    {
                        var nonZeroActions = healingHistoryList.Where(d => !d.Key.Contains("•"));
                        var keyValuePairs  = nonZeroActions as IList <KeyValuePair <string, decimal> > ?? nonZeroActions.ToList();
                        var healing        = 0m;
                        switch (regen)
                        {
                        case true:
                            healing = Math.Ceiling(((amount / resolvedPotency) * actionData.ActionOverTimePotency) / 3);
                            break;

                        case false:
                            if (keyValuePairs.Any())
                            {
                                amount = keyValuePairs.Sum(action => action.Value);
                                amount = amount / keyValuePairs.Count();
                            }
                            healing = Math.Ceiling(((amount / resolvedPotency) * actionData.ActionOverTimePotency) / 3);
                            break;
                        }
                        tickHealing = healing > 0 ? healing : tickHealing;
                    }
                    var line = new Line
                    {
                        Action         = statusKey,
                        Amount         = tickHealing,
                        EventDirection = EventDirection.Unknown,
                        EventType      = EventType.Cure,
                        EventSubject   = EventSubject.Unknown,
                        Source         = Name
                    };
                    try
                    {
                        var players = Controller.Timeline.Party.ToList();
                        var entry   = statusEntry;
                        foreach (var player in players.Where(player => player.Name.Contains(entry.TargetName)))
                        {
                            line.Target = player.Name;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    if (String.IsNullOrWhiteSpace(line.Target))
                    {
                        line.Target = String.Format("[???] {0}", statusEntry.TargetName);
                    }
                    Controller.Timeline.FightingRightNow = true;
                    Controller.Timeline.FightingTimer.Stop();
                    switch (Settings.Default.StoreHistoryEvent)
                    {
                    case "Any":
                        Controller.Timeline.StoreHistoryTimer.Stop();
                        break;
                    }
                    DispatcherHelper.Invoke(delegate
                    {
                        line.Hit = true;
                        // resolve player hp each tick to ensure they are not at max
                        try
                        {
                            var players = PCWorkerDelegate.GetNPCEntities();
                            if (!players.Any())
                            {
                                return;
                            }
                            foreach (var actorEntity in players)
                            {
                                var playerName = actorEntity.Name;
                                Controller.Timeline.TrySetPlayerCurable(playerName, actorEntity.HPMax - actorEntity.HPCurrent);
                            }
                        }
                        catch (Exception ex)
                        {
                        }
                        var currentCritPercent = (double)Stats.GetStatValue("HealingCritPercent");
                        if (new Random().NextDouble() * 3 < currentCritPercent)
                        {
                            line.Crit   = true;
                            line.Amount = line.Amount * 1.5m;
                        }
                        Controller.Timeline.GetSetPlayer(line.Source)
                        .SetHealingOverTime(line);
                    });
                }
                catch (Exception ex)
                {
                }
            }
            Controller.Timeline.FightingTimer.Start();
            switch (Settings.Default.StoreHistoryEvent)
            {
            case "Any":
                Controller.Timeline.StoreHistoryTimer.Start();
                break;
            }
        }
Esempio n. 5
0
        /// <summary>
        /// </summary>
        /// <param name="statusEntriesMonsters"></param>
        private void ProcessDamageOverTime(IEnumerable <StatusEntry> statusEntriesMonsters)
        {
            foreach (var statusEntry in statusEntriesMonsters)
            {
                try
                {
                    var statusInfo = StatusEffectHelper.StatusInfo(statusEntry.StatusID);
                    var statusKey  = "";
                    switch (Constants.GameLanguage)
                    {
                    case "English":
                        statusKey = statusInfo.Name.English;
                        break;

                    case "French":
                        statusKey = statusInfo.Name.French;
                        break;

                    case "German":
                        statusKey = statusInfo.Name.German;
                        break;

                    case "Japanese":
                        statusKey = statusInfo.Name.Japanese;
                        break;
                    }
                    if (String.IsNullOrWhiteSpace(statusKey))
                    {
                        continue;
                    }
                    var             amount     = NPCEntry.Level / ((60 - NPCEntry.Level) * .025m);
                    var             key        = statusKey;
                    XOverTimeAction actionData = null;
                    foreach (var damageOverTimeAction in DamageOverTimeHelper.PlayerActions.ToList()
                             .Where(d => String.Equals(d.Key, key, Constants.InvariantComparer)))
                    {
                        actionData = damageOverTimeAction.Value;
                    }
                    if (actionData == null)
                    {
                        continue;
                    }
                    var zeroFoundInList           = false;
                    var bio                       = Regex.IsMatch(key, @"(バイオ|bactérie|bio)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
                    var thunder                   = Regex.IsMatch(key, @"(サンダ|foudre|blitz|thunder)", RegexOptions.CultureInvariant | RegexOptions.IgnoreCase);
                    var lastDamageAmountByActions = ParseHelper.LastAmountByAction.GetPlayer(Name)
                                                    .ToList();
                    var resolvedPotency       = 80;
                    var thunderDuration       = 24;
                    var originalThunderDamage = 0m;
                    foreach (var lastDamageAmountByAction in lastDamageAmountByActions)
                    {
                        if (thunder)
                        {
                            var found          = false;
                            var thunderActions = DamageOverTimeHelper.ThunderActions;
                            var action         = lastDamageAmountByAction;
                            if (thunderActions["III"].Any(thunderAction => String.Equals(action.Key, thunderAction, Constants.InvariantComparer)))
                            {
                                found                 = true;
                                thunderDuration       = DamageOverTimeHelper.PlayerActions["thunder iii"].Duration;
                                originalThunderDamage = action.Value;
                                amount                = (action.Value / DamageOverTimeHelper.PlayerActions["thunder iii"].ActionPotency) * 30;
                            }
                            if (thunderActions["II"].Any(thunderAction => String.Equals(action.Key, thunderAction, Constants.InvariantComparer)))
                            {
                                found                 = true;
                                thunderDuration       = DamageOverTimeHelper.PlayerActions["thunder ii"].Duration;
                                originalThunderDamage = action.Value;
                                amount                = (action.Value / DamageOverTimeHelper.PlayerActions["thunder ii"].ActionPotency) * 30;
                            }
                            if (thunderActions["I"].Any(thunderAction => String.Equals(action.Key, thunderAction, Constants.InvariantComparer)))
                            {
                                found                 = true;
                                thunderDuration       = DamageOverTimeHelper.PlayerActions["thunder"].Duration;
                                originalThunderDamage = action.Value;
                                amount                = action.Value;
                            }
                            if (found)
                            {
                                break;
                            }
                        }
                        if (bio)
                        {
                            var found       = false;
                            var ruinActions = DamageOverTimeHelper.RuinActions;
                            var action      = lastDamageAmountByAction;
                            if (ruinActions["II"].Any(ruinAction => String.Equals(action.Key, ruinAction, Constants.InvariantComparer)))
                            {
                                found  = zeroFoundInList = true;
                                amount = action.Value;
                            }
                            if (ruinActions["I"].Any(ruinAction => String.Equals(action.Key, ruinAction, Constants.InvariantComparer)))
                            {
                                found  = zeroFoundInList = true;
                                amount = action.Value;
                            }
                            if (found)
                            {
                                break;
                            }
                        }
                        if (String.Equals(lastDamageAmountByAction.Key, key, Constants.InvariantComparer))
                        {
                            amount = lastDamageAmountByAction.Value;
                            break;
                        }
                    }
                    statusKey = String.Format("{0} [•]", statusKey);
                    if (amount == 0)
                    {
                        amount = 75;
                    }
                    resolvedPotency = zeroFoundInList ? resolvedPotency : bio ? resolvedPotency : actionData.ActionPotency;
                    var tickDamage = Math.Ceiling(((amount / resolvedPotency) * actionData.ActionOverTimePotency) / 3);
                    if (actionData.HasNoInitialResult && !zeroFoundInList)
                    {
                        var nonZeroActions = lastDamageAmountByActions.Where(d => !d.Key.Contains("•"));
                        var keyValuePairs  = nonZeroActions as IList <KeyValuePair <string, decimal> > ?? nonZeroActions.ToList();
                        var damage         = 0m;
                        switch (bio)
                        {
                        case true:
                            damage = Math.Ceiling(((amount / resolvedPotency) * actionData.ActionOverTimePotency) / 3);
                            break;

                        case false:
                            if (keyValuePairs.Any())
                            {
                                amount = keyValuePairs.Sum(action => action.Value);
                                amount = amount / keyValuePairs.Count();
                            }
                            damage = Math.Ceiling(((amount / resolvedPotency) * actionData.ActionOverTimePotency) / 3);
                            break;
                        }
                        tickDamage = damage > 0 ? damage : tickDamage;
                    }
                    if (originalThunderDamage > 300 && thunder)
                    {
                        tickDamage = Math.Ceiling(originalThunderDamage / (thunderDuration + 3));
                    }
                    var line = new Line
                    {
                        Action         = statusKey,
                        Amount         = tickDamage,
                        EventDirection = EventDirection.Unknown,
                        EventType      = EventType.Damage,
                        EventSubject   = EventSubject.Unknown,
                        Source         = Name,
                        Target         = statusEntry.TargetName
                    };
                    Controller.Timeline.FightingRightNow = true;
                    Controller.Timeline.FightingTimer.Stop();
                    Controller.Timeline.StoreHistoryTimer.Stop();
                    DispatcherHelper.Invoke(delegate
                    {
                        line.Hit = true;
                        var currentCritPercent = (double)Stats.GetStatValue("DamageCritPercent");
                        if (new Random().NextDouble() * 3 < currentCritPercent)
                        {
                            line.Crit   = true;
                            line.Amount = line.Amount * 1.5m;
                        }
                        Controller.Timeline.GetSetPlayer(line.Source)
                        .SetDamageOverTime(line);
                        Controller.Timeline.GetSetMonster(line.Target)
                        .SetDamageTakenOverTime(line);
                    });
                }
                catch (Exception ex)
                {
                }
            }
            Controller.Timeline.FightingTimer.Start();
            Controller.Timeline.StoreHistoryTimer.Start();
        }
 public void Test_DispatcherHelper_Action_Null()
 {
     DispatcherHelper.ExecuteOnUIThreadAsync(default(Action));
 }
Esempio n. 7
0
 /// <summary>
 ///     导航。
 /// </summary>
 public void Navigate(Type sourcePageType)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(() => {
         ((Frame)Window.Current.Content).Navigate(sourcePageType);
     });
 }
Esempio n. 8
0
 private void AddErrorLog(string data)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(() => this.Logs.Add("ERROR: " + data));
     this.logger.Error(data);
 }
Esempio n. 9
0
 private void OpenOrders_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(() => CalculatePNL());
 }
        private void ThreadRun()
        {
            _mainTask.Start();

            _mainTask.RegisterRoot();

            var config = new ConfigWrapper(workingDirectory);

            var doAWC = !args.Contains("runonly") || args.GetStringDefault("runonly", "").ToLower() == "awc";
            var doDPS = !args.Contains("runonly") || args.GetStringDefault("runonly", "").ToLower() == "dips";
            var doTVC = !args.Contains("runonly") || args.GetStringDefault("runonly", "").ToLower() == "tvc";
            var doCSE = !args.Contains("runonly") || args.GetStringDefault("runonly", "").ToLower() == "cse";

            config.load(logger);


            var awc  = new AutoWallChange(logger, config.settings.awc, workingDirectory);
            var dips = new DesktopIconPositionSaver(logger, config.settings.dips, workingDirectory);
            var tvc  = new TextVersionControl(logger, config.settings.tvc, workingDirectory);
            var cse  = new CronScriptExecutor(logger, config.settings.cse, workingDirectory);

            // =====================================================================================================

            ATCTaskProxy taskAWC = null;
            ATCTaskProxy taskDPS = null;
            ATCTaskProxy taskTVC = null;
            ATCTaskProxy taskCSE = null;

            var newtasks = new List <ATCTaskProxy>();

            if (doAWC)
            {
                newtasks.Add(taskAWC = new ATCTaskProxy("AutoWallChange", "AWC"));
            }
            if (doDPS)
            {
                newtasks.Add(taskDPS = new ATCTaskProxy("DesktopIconPositionSaver", "DIPS"));
            }
            if (doTVC)
            {
                newtasks.Add(taskTVC = new ATCTaskProxy("TextVersionControl", "TVC"));
            }
            if (doCSE)
            {
                newtasks.Add(taskCSE = new ATCTaskProxy("CronScriptExecutor", "CSE"));
            }

            if (doAWC)
            {
                newtasks.AddRange(awc.Init(taskAWC));
            }
            if (doDPS)
            {
                newtasks.AddRange(dips.Init(taskDPS));
            }
            if (doTVC)
            {
                newtasks.AddRange(tvc.Init(taskTVC));
            }
            if (doCSE)
            {
                newtasks.AddRange(cse.Init(taskCSE));
            }

            foreach (var t in newtasks)
            {
                DispatcherHelper.SmartInvoke(() => { _vm.Tasks.Add(t); });
                Thread.Sleep(25);
            }

            // =====================================================================================================

            if (doAWC)
            {
                taskAWC.Start();
                awc.Start();
                taskAWC.FinishSuccess();
                Thread.Sleep(100);
            }

            if (doDPS)
            {
                taskDPS.Start();
                dips.Start();
                taskDPS.FinishSuccess();
                Thread.Sleep(100);
            }

            if (doTVC)
            {
                taskTVC.Start();
                tvc.Start();
                taskTVC.FinishSuccess();
                Thread.Sleep(100);
            }

            if (doCSE)
            {
                taskCSE.Start();
                cse.Start();
                taskCSE.FinishSuccess();
                Thread.Sleep(100);
            }

            // =====================================================================================================

            config.save();

            _mainTask.FinishSuccess();

            logger.SaveAll();

            if (_vm.Tasks.All(p => p.State == ProxyState.Success))
            {
                _isAutoClosing = true;

                var max = 10 * 1000;

                new Thread(() =>
                {
                    var start = Environment.TickCount;
                    for (; ;)
                    {
                        if (_abortAutoClosing)
                        {
                            DispatcherHelper.SmartInvoke(() => { _vm.CloseProgress = 0; });
                            return;
                        }

                        var delta = Environment.TickCount - start;

                        if (delta > max)
                        {
                            DispatcherHelper.SmartInvoke(() => { App.Current.MainWindow.Close(); });
                            return;
                        }
                        else
                        {
                            var p = ((delta * 100) / max);
                            if (p != _vm.CloseProgress)
                            {
                                DispatcherHelper.SmartInvoke(() => { _vm.CloseProgress = p; });
                            }
                        }

                        Thread.Yield();
                    }
                }).Start();
            }
        }
Esempio n. 11
0
        /// <summary>
        /// Loads stream items from the souncloud api
        /// </summary>
        /// <param name="count">The amount of items to load</param>
        // ReSharper disable once RedundantAssignment
        public IAsyncOperation <LoadMoreItemsResult> LoadMoreItemsAsync(uint count)
        {
            // Return a task that will get the items
            return(Task.Run(async() =>
            {
                // We are loading
                await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.IsLoading = true; });

                // Get the resource loader
                var resources = ResourceLoader.GetForViewIndependentUse();

                // Check if the user is not logged in
                if (SoundByteService.Current.IsSoundCloudAccountConnected)
                {
                    try
                    {
                        // Get all the users notifications
                        var notifications = await SoundByteService.Current.GetAsync <NotificationListHolder>("/activities", new Dictionary <string, string>
                        {
                            { "limit", "50" },
                            { "linked_partitioning", "1" },
                            { "offset", Token }
                        }, true);

                        // Parse uri for offset
                        var param = new QueryParameterCollection(notifications.NextList);
                        var offset = param.FirstOrDefault(x => x.Key == "offset").Value;

                        // Get the notifications offset
                        Token = string.IsNullOrEmpty(offset) ? "eol" : offset;

                        // Make sure that there are notifications in the list
                        if (notifications.Notifications.Count > 0)
                        {
                            // Set the count variable
                            count = (uint)notifications.Notifications.Count;

                            // Loop though all the notifications on the UI thread
                            await DispatcherHelper.ExecuteOnUIThreadAsync(() =>
                            {
                                notifications.Notifications.ForEach(Add);
                            });
                        }
                        else
                        {
                            // There are no items, so we added no items
                            count = 0;

                            // Reset the token
                            Token = "eol";

                            // No items tell the user
                            await DispatcherHelper.ExecuteOnUIThreadAsync(async() =>
                            {
                                await new MessageDialog(resources.GetString("Notifications_Content"), resources.GetString("Notifications_Header")).ShowAsync();
                            });
                        }
                    }
                    catch (SoundByteException ex)
                    {
                        // Exception, most likely did not add any new items
                        count = 0;

                        // Reset the token
                        Token = "eol";

                        // Exception, display error to the user
                        await DispatcherHelper.ExecuteOnUIThreadAsync(async() =>
                        {
                            await new MessageDialog(ex.ErrorDescription, ex.ErrorTitle).ShowAsync();
                        });
                    }
                }
                else
                {
                    // Not logged in, so no new items
                    count = 0;

                    // Reset the token
                    Token = "eol";

                    // No items tell the user
                    await DispatcherHelper.ExecuteOnUIThreadAsync(async() =>
                    {
                        await new MessageDialog(resources.GetString("ErrorControl_LoginFalse_Content"), resources.GetString("ErrorControl_LoginFalse_Header")).ShowAsync();
                    });
                }

                // We are not loading
                await DispatcherHelper.ExecuteOnUIThreadAsync(() => { App.IsLoading = false; });

                // Return the result
                return new LoadMoreItemsResult {
                    Count = count
                };
            }).AsAsyncOperation());
        }
Esempio n. 12
0
        static App()
        {
            GraphicsManager.LoadSettings();

            DispatcherHelper.Initialize();
        }
Esempio n. 13
0
        public async Task FileUpload(List <StorageFile> imgList, bool isDeleteFiles = false)
        {
            if (imgList.Count > 0)
            {
                // 弹出组选择框
                var groupDialog = new GroupDialog();
                groupDialog.PrimaryButtonClick += async(_s, _e) =>
                {
                    // 选定分组后,上传图片
                    if (groupDialog.SelectGroup != null)
                    {
                        var errorFile = new List <StorageFile>();
                        UploadInfoCollection.Clear();
                        UploadProgressCollection.Clear();
                        var imgItemList = new List <OneDriveImage>();
                        var imgTemp     = await AppTools.ConvertFileToImage(imgList[0]);

                        // 如果仅一张图片上传,则显示该图片的分辨率、大小等信息
                        if (imgList.Count == 1)
                        {
                            var fileInfo = await imgList[0].GetBasicPropertiesAsync();

                            UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("RP"), imgTemp.PixelWidth + "x" + imgTemp.PixelHeight));
                            UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("ImageSize"), Math.Round((fileInfo.Size / (1024.0 * 1024.0)), 1) + "M"));
                            UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("ImageType"), Path.GetExtension(imgList[0].Path).Substring(1).ToUpper()));
                            UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("CreateDate"), fileInfo.DateModified.ToString("yyyy/MM/dd")));
                        }
                        // 如果有多张图片上传,则显示总览信息
                        else
                        {
                            double size = 0;
                            foreach (var item in imgList)
                            {
                                var fileInfo = await item.GetBasicPropertiesAsync();

                                size += Math.Round((fileInfo.Size / (1024.0 * 1024.0)), 1);
                            }
                            UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("ImageCount"), imgList.Count.ToString()));
                            UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("GroupName"), groupDialog.SelectGroup.GroupName));
                            UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("AllSize"), size + "M"));
                        }
                        // 将上传列表的第一张图片作为上传区域背景
                        var backBrush = new ImageBrush();
                        backBrush.Stretch     = Stretch.UniformToFill;
                        backBrush.ImageSource = imgTemp;
                        UploadArea.Background = backBrush;
                        // 隐藏上传提示字符
                        UploadAreaHold.Visibility = Visibility.Collapsed;
                        double uploadColumnWidth = UploadColumn.ActualWidth - 30;
                        // 根据上传信息显示的数目来确定单一信息所占区域大小
                        UploadInfoWidth = uploadColumnWidth / UploadInfoCollection.Count;
                        // 装载进度条
                        for (int i = 0; i < imgList.Count; i++)
                        {
                            var item = imgList[i];
                            UploadProgressCollection.Add(new ProgressStatus(i + 1, item.DisplayName));
                        }
                        var tasks = new List <Task>();
                        // 开始逐一上传图片
                        foreach (var item in imgList)
                        {
                            tasks.Add(Task.Run(async() =>
                            {
                                await DispatcherHelper.ExecuteOnUIThreadAsync(async() =>
                                {
                                    var img = await App.OneDriveTools.UploadImage(item, groupDialog.SelectGroup);
                                    // 图片若上传错误,则加入错误文件列表中
                                    if (img == null)
                                    {
                                        errorFile.Add(item);
                                    }
                                    // 否则,写入成功列表
                                    else
                                    {
                                        imgItemList.Add(img);
                                        LastestImageCollection.Insert(0, img);
                                        if (LastestNoDataTipBlock.Visibility == Visibility.Visible)
                                        {
                                            LastestNoDataTipBlock.Visibility = Visibility.Collapsed;
                                            LastestListView.Visibility       = Visibility.Visible;
                                        }
                                        for (int j = UploadProgressCollection.Count - 1; j >= 0; j--)
                                        {
                                            if (UploadProgressCollection[j].Name.Replace($"[{j + 1}] ", "") == item.DisplayName)
                                            {
                                                UploadProgressCollection.RemoveAt(j);
                                            }
                                        }
                                        if (isDeleteFiles)
                                        {
                                            await item.DeleteAsync();
                                        }
                                    }
                                });
                            }));
                        }
                        await Task.WhenAll(tasks.ToArray());

                        // 所有任务上传完成,清空背景,加入占位符
                        var res   = App.Current.RequestedTheme == ApplicationTheme.Dark ? (ResourceDictionary)App.Current.Resources.ThemeDictionaries["Dark"] : (ResourceDictionary)App.Current.Resources.ThemeDictionaries["Light"];
                        var color = (SolidColorBrush)res["MainBackground"];
                        UploadArea.Background     = color;
                        UploadAreaHold.Visibility = Visibility.Visible;
                        // 恢复默认上传信息
                        UploadInfoCollection.Clear();
                        UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("DefaultUploadInfoTitle"), AppTools.GetReswLanguage("None")));
                        UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("ImageSize"), AppTools.GetReswLanguage("None")));
                        UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("ImageType"), AppTools.GetReswLanguage("None")));
                        UploadInfoCollection.Add(new KeyValue(AppTools.GetReswLanguage("CreateDate"), AppTools.GetReswLanguage("None")));
                        UploadInfoWidth = uploadColumnWidth / UploadInfoCollection.Count;
                        // 清除上传进度条
                        UploadProgressCollection.Clear();

                        // 当成功列表中有数据时,显示成功数目,并将成功上传的图片反映在UI上
                        if (imgItemList.Any())
                        {
                            int num = await App.OneDriveTools.AddImageToDatabase(App.Db, imgItemList);

                            string msg = AppTools.GetReswLanguage("AddImageSuccess").Replace("{count}", num.ToString());
                            new PopupMaskTip(msg).Show();
                            AppTools.WriteLocalSetting(AppSettings.SelectGroupIndex, groupDialog.SelectGroup.GroupId);
                            GroupInit(groupDialog.SelectGroup);
                        }
                        // 如果错误列表中有数据,则提醒用户
                        if (errorFile.Any())
                        {
                            int    num       = errorFile.Count;
                            string msg       = AppTools.GetReswLanguage("AddImageFailed").Replace("{count}", num.ToString());
                            var    tipDialog = new TipDialog(AppTools.GetReswLanguage("AddFailTitle"), msg);
                            await tipDialog.ShowAsync();
                        }
                    }
                };
                await groupDialog.ShowAsync();
            }
        }
Esempio n. 14
0
 private void App_Startup(object sender, StartupEventArgs e)
 {
     DispatcherHelper.Initialize();
 }
Esempio n. 15
0
 public VMBase()
 {
     DispatcherHelper.Initialize();
 }
Esempio n. 16
0
 private void UpdateLanguage(OnLanguageChanged onLanguageChanged = null)
 {
     DispatcherHelper.CheckBeginInvokeOnUI((Action)(() => this.UpdateProgramUpdatingText = this._languageService.GetString("UpdateProgramUpdatingText")));
 }
Esempio n. 17
0
        /// <summary>
        /// Animates a point light and it's distance.
        /// </summary>
        /// <param name="animationSet">The animation set.</param>
        /// <param name="distance">The distance of the light.</param>
        /// <param name="duration">The duration in milliseconds.</param>
        /// <param name="delay">The delay. (ignored if duration == 0)</param>
        /// <seealso cref="IsLightingSupported" />
        /// <returns>
        /// An Animation Set.
        /// </returns>
        public static AnimationSet Light(
            this AnimationSet animationSet,
            double distance = 0d,
            double duration = 500d,
            double delay    = 0d)
        {
            if (!IsLightingSupported)
            {
                return(null);
            }

            if (animationSet == null)
            {
                return(null);
            }

            var visual           = animationSet.Visual;
            var associatedObject = animationSet.Element as FrameworkElement;

            if (associatedObject == null)
            {
                return(animationSet);
            }

            var compositor = visual?.Compositor;

            if (compositor == null)
            {
                return(null);
            }

            var task = new AnimationTask();

            task.AnimationSet = animationSet;

            task.Task = DispatcherHelper.ExecuteOnUIThreadAsync(
                () =>
            {
                const string sceneName = "PointLightScene";
                PointLight pointLight;
                CompositionDrawingSurface normalMap = null;

                if (!pointLights.ContainsKey(visual))
                {
                    SurfaceLoader.Initialize(compositor);
                    normalMap = SurfaceLoader.LoadText(string.Empty, new Windows.Foundation.Size(512, 512), new Graphics.Canvas.Text.CanvasTextFormat(), Colors.Transparent, Colors.Transparent);
                }

                if (pointLights.ContainsKey(visual))
                {
                    pointLight = pointLights[visual];
                }
                else
                {
                    pointLight = compositor.CreatePointLight();

                    var normalBrush     = compositor.CreateSurfaceBrush(normalMap);
                    normalBrush.Stretch = CompositionStretch.Fill;

                    // check to see if the visual already has a point light applied.
                    var spriteVisual = ElementCompositionPreview.GetElementChildVisual(associatedObject) as SpriteVisual;
                    var normalsBrush = spriteVisual?.Brush as CompositionEffectBrush;

                    if (normalsBrush == null || normalsBrush.Comment != sceneName)
                    {
                        var lightEffect = new CompositeEffect()
                        {
                            Mode    = CanvasComposite.Add,
                            Sources =
                            {
                                new CompositionEffectSourceParameter("ImageSource"),
                                new SceneLightingEffect()
                                {
                                    Name            = sceneName,
                                    AmbientAmount   = 0,
                                    DiffuseAmount   = 0.5f,
                                    SpecularAmount  = 0,
                                    NormalMapSource = new CompositionEffectSourceParameter("NormalMap"),
                                }
                            }
                        };

                        var effectFactory = compositor.CreateEffectFactory(lightEffect);
                        var brush         = effectFactory.CreateBrush();
                        brush.SetSourceParameter("NormalMap", normalBrush);

                        var sprite     = compositor.CreateSpriteVisual();
                        sprite.Size    = visual.Size;
                        sprite.Brush   = brush;
                        sprite.Comment = sceneName;

                        ElementCompositionPreview.SetElementChildVisual(task.AnimationSet.Element, sprite);

                        pointLight.CoordinateSpace = visual;
                        pointLight.Targets.Add(visual);
                    }
                }

                var delayTime    = task.Delay != null ? task.Delay.Value : TimeSpan.FromMilliseconds(delay);
                var durationTime = task.Duration != null ? task.Duration.Value : TimeSpan.FromMilliseconds(duration);

                if (durationTime.TotalMilliseconds <= 0)
                {
                    task.AnimationSet.AddEffectDirectPropertyChange(pointLight, (float)distance, nameof(pointLight.Offset));
                }
                else
                {
                    var diffuseAnimation = compositor.CreateVector3KeyFrameAnimation();
                    diffuseAnimation.InsertKeyFrame(1f, new System.Numerics.Vector3(visual.Size.X / 2, visual.Size.Y / 2, (float)distance));
                    diffuseAnimation.Duration  = durationTime;
                    diffuseAnimation.DelayTime = delayTime;

                    task.AnimationSet.AddCompositionEffectAnimation(pointLight, diffuseAnimation, nameof(pointLight.Offset));
                }

                pointLights[visual] = pointLight;
            }, Windows.UI.Core.CoreDispatcherPriority.Normal);

            animationSet.AddAnimationThroughTask(task);
            return(animationSet);
        }
Esempio n. 18
0
 protected void InvokeOnUI(Action action)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(action);
 }
Esempio n. 19
0
 public void CheckBeginInvokeOnUi(Action action)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(action);
 }
Esempio n. 20
0
 protected async void OnPropertyChanged([CallerMemberName] string propertyName = null)
 {
     await DispatcherHelper.ExecuteOnUIThreadAsync(() => PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName))).ConfigureAwait(false);
 }
Esempio n. 21
0
 private void AddInfoLog(string data)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(() => this.Logs.Add(data));
     this.logger.Info(data);
 }
Esempio n. 22
0
        private void OnUserJoined(UserInfoModel infoModel)
        {
            var userModel = new UserModel(infoModel.UserName, infoModel.Image);

            DispatcherHelper.CheckBeginInvokeOnUI(() => UserModels.Add(userModel));
        }
Esempio n. 23
0
 private void CloseTrade(OrderViewModel obj)
 {
     OpenOrders.Remove(obj);
     ClosedOrders.Add(obj);
     DispatcherHelper.CheckBeginInvokeOnUI(() => CalculatePNL());
 }
Esempio n. 24
0
        private void OnSceneObjectCreated(SceneObjectInfoModel infoModel)
        {
            SceneObjectModel model = null;

            switch (infoModel.SceneObjectType)
            {
            case SceneObjectType.Teapot:
                model = new SceneObjectModel(new Teapot()
                {
                    Name = infoModel.Name
                }, infoModel.Id);
                break;

            case SceneObjectType.Cube:
                model = new SceneObjectModel(new Cube()
                {
                    Name = infoModel.Name
                }, infoModel.Id);
                break;

            case SceneObjectType.Cylinder:
                model = new SceneObjectModel(new Cylinder()
                {
                    Name = infoModel.Name
                }, infoModel.Id);
                break;

            case SceneObjectType.Disk:
                model = new SceneObjectModel(new Disk()
                {
                    Name = infoModel.Name
                }, infoModel.Id);
                break;

            case SceneObjectType.Sphere:
                model = new SceneObjectModel(new Sphere()
                {
                    Name = infoModel.Name
                }, infoModel.Id);
                break;

            default:
                break;
            }

            if (infoModel.Transformation != null)
            {
                var transformation = model.Transformation;

                transformation.TranslateX = infoModel.Transformation.TranslateX;
                transformation.TranslateY = infoModel.Transformation.TranslateY;
                transformation.TranslateZ = infoModel.Transformation.TranslateZ;

                transformation.RotateX = infoModel.Transformation.RotateX;
                transformation.RotateY = infoModel.Transformation.RotateY;
                transformation.RotateZ = infoModel.Transformation.RotateZ;

                transformation.ScaleX = infoModel.Transformation.ScaleX;
                transformation.ScaleY = infoModel.Transformation.ScaleY;
                transformation.ScaleZ = infoModel.Transformation.ScaleZ;
            }

            DispatcherHelper.RunAsync(() => SceneObjectModels.Add(model));
        }
Esempio n. 25
0
 private void CommunicationService_ChartInfo(object sender, ChartInfo e)
 {
     this.ChartInfo = e;
     IsChartLocked  = true;
     DispatcherHelper.CheckBeginInvokeOnUI(() => CommandManager.InvalidateRequerySuggested());
 }
Esempio n. 26
0
        public async Task AddMessage(ChatMessageViewModel message)
        {
            message.ProcessingStartTime = DateTimeOffset.Now;
            Logger.Log(LogLevel.Debug, string.Format("Message Received - {0} - {1} - {2}", message.ID.ToString(), message.ProcessingStartTime, message));

            // Pre message processing

            if (message is UserChatMessageViewModel)
            {
                if (message.User != null)
                {
                    if (message.Platform == StreamingPlatformTypeEnum.Twitch)
                    {
                        UserViewModel activeUser = ChannelSession.Services.User.GetUserByTwitchID(message.User.TwitchID);
                        if (activeUser != null)
                        {
                            message.User = activeUser;
                        }
                    }

                    message.User.UpdateLastActivity();
                    if (message.IsWhisper && ChannelSession.Settings.TrackWhispererNumber && !message.IsStreamerOrBot && message.User.WhispererNumber == 0)
                    {
                        await this.whisperNumberLock.WaitAndRelease(() =>
                        {
                            if (!whisperMap.ContainsKey(message.User.ID))
                            {
                                whisperMap[message.User.ID] = whisperMap.Count + 1;
                            }
                            message.User.WhispererNumber = whisperMap[message.User.ID];
                            return(Task.FromResult(0));
                        });
                    }
                }
            }

            // Add message to chat list
            bool showMessage = true;

            if (ChannelSession.Settings.HideBotMessages && ChannelSession.TwitchBotNewAPI != null && message.User.TwitchID.Equals(ChannelSession.TwitchBotNewAPI.id))
            {
                showMessage = false;
            }

            if (!(message is AlertChatMessageViewModel) || !ChannelSession.Settings.OnlyShowAlertsInDashboard)
            {
                await DispatcherHelper.InvokeDispatcher(() =>
                {
                    this.messagesLookup[message.ID] = message;
                    if (showMessage)
                    {
                        if (ChannelSession.Settings.LatestChatAtTop)
                        {
                            this.Messages.Insert(0, message);
                        }
                        else
                        {
                            this.Messages.Add(message);
                        }
                    }

                    if (this.Messages.Count > ChannelSession.Settings.MaxMessagesInChat)
                    {
                        ChatMessageViewModel removedMessage = (ChannelSession.Settings.LatestChatAtTop) ? this.Messages.Last() : this.Messages.First();
                        this.messagesLookup.Remove(removedMessage.ID);
                        this.Messages.Remove(removedMessage);
                    }

                    return(Task.FromResult(0));
                });
            }

            // Post message processing

            if (message is UserChatMessageViewModel)
            {
                if (message.IsWhisper && !message.IsStreamerOrBot)
                {
                    if (!string.IsNullOrEmpty(ChannelSession.Settings.NotificationChatWhisperSoundFilePath))
                    {
                        await ChannelSession.Services.AudioService.Play(ChannelSession.Settings.NotificationChatWhisperSoundFilePath, ChannelSession.Settings.NotificationChatWhisperSoundVolume, ChannelSession.Settings.NotificationsAudioOutput);
                    }

                    if (!string.IsNullOrEmpty(message.PlainTextMessage))
                    {
                        EventTrigger trigger = new EventTrigger(EventTypeEnum.ChatWhisperReceived, message.User);
                        trigger.SpecialIdentifiers["message"] = message.PlainTextMessage;
                        await ChannelSession.Services.Events.PerformEvent(trigger);
                    }

                    // Don't send this if it's in response to another "You are whisperer #" message
                    if (ChannelSession.Settings.TrackWhispererNumber && message.User.WhispererNumber > 0 && !message.PlainTextMessage.StartsWith("You are whisperer #", StringComparison.InvariantCultureIgnoreCase))
                    {
                        await ChannelSession.Services.Chat.Whisper(message.User, $"You are whisperer #{message.User.WhispererNumber}.", sendAsStreamer : false);
                    }
                }
                else
                {
                    if (this.DisableChat)
                    {
                        Logger.Log(LogLevel.Debug, string.Format("Deleting Message As Chat Disabled - {0} - {1}", message.ID, message));
                        await this.DeleteMessage(message);

                        return;
                    }

                    if (!string.IsNullOrEmpty(ChannelSession.Settings.NotificationChatTaggedSoundFilePath) && message.IsStreamerTagged)
                    {
                        await ChannelSession.Services.AudioService.Play(ChannelSession.Settings.NotificationChatTaggedSoundFilePath, ChannelSession.Settings.NotificationChatTaggedSoundVolume, ChannelSession.Settings.NotificationsAudioOutput);
                    }
                    else if (!string.IsNullOrEmpty(ChannelSession.Settings.NotificationChatMessageSoundFilePath))
                    {
                        await ChannelSession.Services.AudioService.Play(ChannelSession.Settings.NotificationChatMessageSoundFilePath, ChannelSession.Settings.NotificationChatMessageSoundVolume, ChannelSession.Settings.NotificationsAudioOutput);
                    }

                    if (!this.userEntranceCommands.Contains(message.User.ID))
                    {
                        this.userEntranceCommands.Add(message.User.ID);
                        if (message.User.Data.EntranceCommand != null)
                        {
                            await message.User.Data.EntranceCommand.Perform(message.User, message.Platform);
                        }
                    }

                    if (!string.IsNullOrEmpty(message.PlainTextMessage))
                    {
                        EventTrigger trigger = new EventTrigger(EventTypeEnum.ChatMessageReceived, message.User);
                        trigger.SpecialIdentifiers["message"] = message.PlainTextMessage;
                        await ChannelSession.Services.Events.PerformEvent(trigger);
                    }

                    message.User.Data.TotalChatMessageSent++;

                    string primaryTaggedUsername = message.PrimaryTaggedUsername;
                    if (!string.IsNullOrEmpty(primaryTaggedUsername))
                    {
                        UserViewModel primaryTaggedUser = ChannelSession.Services.User.GetUserByUsername(primaryTaggedUsername, message.Platform);
                        if (primaryTaggedUser != null)
                        {
                            primaryTaggedUser.Data.TotalTimesTagged++;
                        }
                    }
                }

                await message.User.RefreshDetails();

                if (!message.IsWhisper && await message.CheckForModeration())
                {
                    await this.DeleteMessage(message);

                    return;
                }

                IEnumerable <string> arguments = null;
                if (ChannelSession.IsStreamer && !string.IsNullOrEmpty(message.PlainTextMessage) && message.User != null && !message.User.UserRoles.Contains(UserRoleEnum.Banned))
                {
                    if (!ChannelSession.Settings.AllowCommandWhispering && message.IsWhisper)
                    {
                        return;
                    }

                    if (ChannelSession.Settings.IgnoreBotAccountCommands)
                    {
                        if (ChannelSession.TwitchBotNewAPI != null && message.User.TwitchID.Equals(ChannelSession.TwitchBotNewAPI.id))
                        {
                            return;
                        }
                    }

                    Logger.Log(LogLevel.Debug, string.Format("Checking Message For Command - {0} - {1}", message.ID, message));

                    List <PermissionsCommandBase> commands = this.chatCommands.ToList();
                    foreach (PermissionsCommandBase command in message.User.Data.CustomCommands.Where(c => c.IsEnabled))
                    {
                        commands.Add(command);
                    }

                    foreach (PermissionsCommandBase command in commands)
                    {
                        if (command.DoesTextMatchCommand(message.PlainTextMessage, out arguments))
                        {
                            if (command.IsEnabled)
                            {
                                Logger.Log(LogLevel.Debug, string.Format("Command Found For Message - {0} - {1} - {2}", message.ID, message, command));
                                await command.Perform(message.User, message.Platform, arguments : arguments);

                                if (command.Requirements.Settings.DeleteChatCommandWhenRun || (ChannelSession.Settings.DeleteChatCommandsWhenRun && !command.Requirements.Settings.DontDeleteChatCommandWhenRun))
                                {
                                    await this.DeleteMessage(message);
                                }
                            }
                            break;
                        }
                    }
                }

                foreach (InventoryModel inventory in ChannelSession.Settings.Inventory.Values.ToList())
                {
                    if (inventory.ShopEnabled && CommandBase.DoesTextMatchCommand(message.PlainTextMessage, CommandBase.CommandMatchingRegexFormat, new List <string>()
                    {
                        inventory.ShopCommand
                    }, out arguments))
                    {
                        await inventory.PerformShopCommand(message.User, arguments, message.Platform);
                    }
                    else if (inventory.TradeEnabled && CommandBase.DoesTextMatchCommand(message.PlainTextMessage, CommandBase.CommandMatchingRegexFormat, new List <string>()
                    {
                        inventory.TradeCommand
                    }, out arguments))
                    {
                        string args = message.PlainTextMessage.Replace(inventory.TradeCommand, "");
                        await inventory.PerformTradeCommand(message.User, arguments, message.Platform);
                    }
                }

                if (ChannelSession.Settings.RedemptionStoreEnabled)
                {
                    if (CommandBase.DoesTextMatchCommand(message.PlainTextMessage, CommandBase.CommandMatchingRegexFormat, new List <string>()
                    {
                        ChannelSession.Settings.RedemptionStoreChatPurchaseCommand
                    }, out arguments))
                    {
                        await RedemptionStorePurchaseModel.Purchase(message.User, arguments);
                    }
                    else if (CommandBase.DoesTextMatchCommand(message.PlainTextMessage, CommandBase.CommandMatchingRegexFormat, new List <string>()
                    {
                        ChannelSession.Settings.RedemptionStoreModRedeemCommand
                    }, out arguments))
                    {
                        await RedemptionStorePurchaseModel.Redeem(message.User, arguments);
                    }
                }

                GlobalEvents.ChatMessageReceived(message);

                await this.WriteToChatEventLog(message);
            }

            Logger.Log(LogLevel.Debug, string.Format("Message Processing Complete: {0} - {1} ms", message.ID, message.ProcessingTime));
            if (message.ProcessingTime > 500)
            {
                Logger.Log(LogLevel.Error, string.Format("Long processing time detected for the following message: {0} - {1} ms - {2}", message.ID.ToString(), message.ProcessingTime, message));
            }
        }
 public void Test_DispatcherHelper_FuncOfT_Null()
 {
     DispatcherHelper.ExecuteOnUIThreadAsync(default(Func <int>));
 }
        internal MainWindow(INavigator navigator, Settings settings, ProcessService processService, bool isClosedAfterStartingProcess)
        {
            Ensure.NotNull(navigator, "navigator");
            Ensure.NotNull(settings, "settings");
            Ensure.NotNull(processService, "processService");
            this.navigator = navigator;
            this.settings = settings;
            this.processService = processService;
            this.isClosedAfterStartingProcess = isClosedAfterStartingProcess;

            InitializeComponent();
            EventManager.FilePinned += OnFilePinned;
            DispatcherHelper = new DispatcherHelper(Dispatcher);

            fileThrottler = new ThrottlingHelper(DispatcherHelper, () => lvwFiles.SelectedIndex = 0, 0);
            applicationThrottler = new ThrottlingHelper(DispatcherHelper, () => lvwApplications.SelectedIndex = 0, 0);
        }
Esempio n. 29
0
 static App()
 {
     DispatcherHelper.Initialize();
 }
 /// <summary>
 /// On pause player
 /// </summary>
 /// <param name="sender"></param>
 /// <param name="e"></param>
 private void OnPausedMedia(object sender, EventArgs e)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(async() => await PauseMedia());
 }
Esempio n. 31
0
        /// <summary>
        /// 在应用程序由最终用户正常启动时进行调用。
        /// 将在启动应用程序以打开特定文件等情况下使用。
        /// </summary>
        /// <param name="e">有关启动请求和过程的详细信息。</param>
        protected override void OnLaunched(LaunchActivatedEventArgs e)
        {
#if DEBUG
            //if (System.Diagnostics.Debugger.IsAttached)
            //{
            //    this.DebugSettings.EnableFrameRateCounter = true;
            //}
#endif

            var view = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().TitleBar;

            // active
            view.BackgroundColor = Color.FromArgb(255, 8, 87, 180);
            view.ForegroundColor = Colors.White;

            // inactive
            view.InactiveBackgroundColor = Color.FromArgb(255, 8, 87, 180);
            view.InactiveForegroundColor = Colors.White;

            // button
            view.ButtonBackgroundColor = Color.FromArgb(255, 8, 87, 180);
            view.ButtonForegroundColor = Colors.White;

            view.ButtonHoverBackgroundColor = Colors.Blue;
            view.ButtonHoverForegroundColor = Colors.White;

            view.ButtonPressedBackgroundColor = Colors.Blue;
            view.ButtonPressedForegroundColor = Colors.White;

            view.ButtonInactiveBackgroundColor = Color.FromArgb(255, 8, 87, 180);
            view.ButtonInactiveForegroundColor = Colors.White;

            //Frame rootFrame = Window.Current.Content as Frame;

            //// 不要在窗口已包含内容时重复应用程序初始化,
            //// 只需确保窗口处于活动状态
            //if (rootFrame == null)
            //{
            //    // 创建要充当导航上下文的框架,并导航到第一页
            //    rootFrame = new Frame();

            //    rootFrame.NavigationFailed += OnNavigationFailed;

            //    if (e.PreviousExecutionState == ApplicationExecutionState.Terminated)
            //    {
            //        //TODO: 从之前挂起的应用程序加载状态
            //    }

            //    // 将框架放在当前窗口中
            //    Window.Current.Content = rootFrame;
            //}

            //if (e.PrelaunchActivated == false)
            //{
            //    if (rootFrame.Content == null)
            //    {
            //        // 当导航堆栈尚未还原时,导航到第一页,
            //        // 并通过将所需信息作为导航参数传入来配置
            //        // 参数
            //        rootFrame.Navigate(typeof(MainPage), e.Arguments);
            //    }
            //    // 确保当前窗口处于活动状态
            //    Window.Current.Activate();
            //}

            Window.Current.Content = new MainPage();
            Window.Current.Activate();
            DispatcherHelper.Initialize();

            Messenger.Default.Register <NotificationMessageAction <string> >(
                this,
                HandleNotificationMessage);
        }
Esempio n. 32
0
        private void ProcessBuffs(IEnumerable <StatusEntry> statusEntriesPlayers)
        {
            foreach (var statusEntry in statusEntriesPlayers)
            {
                try
                {
                    var statusInfo = StatusEffectHelper.StatusInfo(statusEntry.StatusID);
                    var statusKey  = "";
                    switch (Constants.GameLanguage)
                    {
                    case "English":
                        statusKey = statusInfo.Name.English;
                        break;

                    case "French":
                        statusKey = statusInfo.Name.French;
                        break;

                    case "German":
                        statusKey = statusInfo.Name.German;
                        break;

                    case "Japanese":
                        statusKey = statusInfo.Name.Japanese;
                        break;
                    }
                    if (String.IsNullOrWhiteSpace(statusKey))
                    {
                        continue;
                    }
                    var line = new Line
                    {
                        Action         = statusKey,
                        Amount         = 0,
                        EventDirection = EventDirection.Unknown,
                        EventType      = EventType.Unknown,
                        EventSubject   = EventSubject.Unknown,
                        Source         = Name,
                    };
                    try
                    {
                        var players = Controller.Timeline.Party.ToList();
                        var entry   = statusEntry;
                        foreach (var player in players.Where(player => player.Name.Contains(entry.TargetName)))
                        {
                            line.Target = player.Name;
                            break;
                        }
                    }
                    catch (Exception ex)
                    {
                    }
                    if (String.IsNullOrWhiteSpace(line.Target))
                    {
                        line.Target = String.Format("[???] {0}", statusEntry.TargetName);
                    }
                    DispatcherHelper.Invoke(() => Controller.Timeline.GetSetPlayer(line.Source)
                                            .SetBuff(line));
                }
                catch (Exception ex)
                {
                }
            }
        }
Esempio n. 33
0
 private void BeginInvokeOnCurrentDispatcher(Action action)
 {
     DispatcherHelper.CheckBeginInvokeOnUI(action);
 }
Esempio n. 34
0
 private void Initialize()
 {
     DispatcherHelper.Initialize();
 }