コード例 #1
0
 public SmartDataGroupsEditorViewModel(ISmartRawDataProvider smartDataProvider, ITaskRunner taskRunner, IMessageBoxService messageBoxService,
                                       IWindowManager windowManager, Func <IHistoryManager> historyCreator, SmartDataSourceMode dataSourceMode)
 {
     this.smartDataProvider = smartDataProvider;
     this.messageBoxService = messageBoxService;
     this.windowManager     = windowManager;
     this.dataSourceMode    = dataSourceMode;
     SourceItems            = new ObservableCollection <SmartDataGroupsEditorData>();
     MakeItems();
     AddGroup = new AsyncAutoCommand(AddGroupToSource);
     Save     = new DelegateCommand(() =>
     {
         taskRunner.ScheduleTask("Saving Group Definitions to file", SaveGroupsToFile);
     });
     DeleteItem = new DelegateCommand <object>(DeleteItemFromSource);
     AddMember  = new AsyncAutoCommand <SmartDataGroupsEditorData>(AddItemToGroup);
     EditItem   = new AsyncAutoCommand <SmartDataGroupsEditorData>(EditSourceItem);
     // history setup
     History                  = historyCreator();
     historyHandler           = new SmartDataGroupsHistory(SourceItems);
     UndoCommand              = new DelegateCommand(History.Undo, () => History.CanUndo);
     RedoCommand              = new DelegateCommand(History.Redo, () => History.CanRedo);
     History.PropertyChanged += (sender, args) =>
     {
         UndoCommand.RaiseCanExecuteChanged();
         RedoCommand.RaiseCanExecuteChanged();
         IsModified = !History.IsSaved;
         RaisePropertyChanged(nameof(IsModified));
     };
     History.AddHandler(historyHandler);
 }
コード例 #2
0
        public SessionServiceViewModel(ISessionService sessionService,
                                       IInputBoxService inputBoxService,
                                       IMessageBoxService messageBoxService,
                                       IWindowManager windowManager,
                                       Lazy <IDocumentManager> documentManager,
                                       ITextDocumentService textDocumentService,
                                       IHistoryManager historyManager)
        {
            this.SessionService    = sessionService;
            this.inputBoxService   = inputBoxService;
            this.messageBoxService = messageBoxService;
            this.windowManager     = windowManager;
            this.History           = historyManager;
            History.AddHandler(this);

            Undo = new DelegateCommand(() => History.Undo(), () => History.CanUndo).ObservesProperty(() =>
                                                                                                     History.CanUndo);
            Redo = new DelegateCommand(() => History.Redo(), () => History.CanRedo).ObservesProperty(() =>
                                                                                                     History.CanRedo);

            NewSessionCommand = new AsyncAutoCommand(NewSession);

            var save = new AsyncAutoCommand(SaveCurrent, _ => sessionService.IsNonEmpty);

            SaveCurrentCurrent = save;

            var forget = new AsyncAutoCommand(ForgetCurrent, _ => sessionService.IsOpened);

            ForgetCurrentCurrent = forget;

            DeleteItem = new DelegateCommand <ISolutionItem>(sessionService.RemoveItem, _ => sessionService.IsOpened).ObservesProperty(() => this.SessionService.IsOpened);

            var preview = new DelegateCommand(() =>
            {
                var sql = sessionService.GenerateCurrentQuery();
                if (sql == null)
                {
                    return;
                }
                documentManager.Value.OpenDocument(textDocumentService.CreateDocument($"Preview of " + sessionService.CurrentSession !.Name, sql, "sql"));
            }, () => sessionService.IsNonEmpty);

            PreviewCurrentCommand = preview;

            sessionService.ToObservable(o => o.IsNonEmpty)
            .SubscribeAction(_ =>
            {
                preview.RaiseCanExecuteChanged();
                forget.RaiseCanExecuteChanged();
                save.RaiseCanExecuteChanged();
            });

            History.ToObservable(h => h.IsSaved)
            .SubscribeAction(_ =>
            {
                PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(IsModified)));
            });
        }
コード例 #3
0
        protected ViewModelBase(IHistoryManager history,
                                DatabaseTableSolutionItem solutionItem,
                                ISolutionItemNameRegistry solutionItemName,
                                ISolutionManager solutionManager,
                                ISolutionTasksService solutionTasksService,
                                IEventAggregator eventAggregator,
                                IQueryGenerator queryGenerator,
                                IDatabaseTableDataProvider databaseTableDataProvider,
                                IMessageBoxService messageBoxService,
                                ITaskRunner taskRunner,
                                IParameterFactory parameterFactory,
                                ITableDefinitionProvider tableDefinitionProvider,
                                IItemFromListProvider itemFromListProvider,
                                ISolutionItemIconRegistry iconRegistry,
                                ISessionService sessionService,
                                IDatabaseTableCommandService commandService,
                                IParameterPickerService parameterPickerService,
                                IStatusBar statusBar,
                                IMySqlExecutor mySqlExecutor)
        {
            this.solutionItemName          = solutionItemName;
            this.solutionManager           = solutionManager;
            this.solutionTasksService      = solutionTasksService;
            this.queryGenerator            = queryGenerator;
            this.databaseTableDataProvider = databaseTableDataProvider;
            this.messageBoxService         = messageBoxService;
            this.taskRunner              = taskRunner;
            this.parameterFactory        = parameterFactory;
            this.tableDefinitionProvider = tableDefinitionProvider;
            this.itemFromListProvider    = itemFromListProvider;
            this.sessionService          = sessionService;
            this.commandService          = commandService;
            this.parameterPickerService  = parameterPickerService;
            this.statusBar     = statusBar;
            this.mySqlExecutor = mySqlExecutor;
            this.solutionItem  = solutionItem;
            History            = history;

            undoCommand            = new DelegateCommand(History.Undo, CanUndo);
            redoCommand            = new DelegateCommand(History.Redo, CanRedo);
            Save                   = new AsyncAutoCommand(SaveSolutionItem);
            title                  = solutionItemName.GetName(solutionItem);
            Icon                   = iconRegistry.GetIcon(solutionItem);
            nameGeneratorParameter = parameterFactory.Factory("Parameter");

            History.PropertyChanged += (_, _) =>
            {
                undoCommand.RaiseCanExecuteChanged();
                redoCommand.RaiseCanExecuteChanged();
                RaisePropertyChanged(nameof(IsModified));
            };

            tableDefinition = tableDefinitionProvider.GetDefinition(solutionItem.DefinitionId) !;
            LoadAndCreateCommands();
            nameGeneratorParameter = parameterFactory.Factory(tableDefinition.Picker);
        }
コード例 #4
0
        public SmartDataDefinesListViewModel(ISmartRawDataProvider smartDataProvider, ISmartDataManager smartDataManager, IParameterFactory parameterFactory,
                                             ITaskRunner taskRunner, IMessageBoxService messageBoxService, IWindowManager windowManager, Func <IHistoryManager> historyCreator, SmartDataSourceMode dataSourceMode)
        {
            this.smartDataProvider = smartDataProvider;
            this.parameterFactory  = parameterFactory;
            this.smartDataManager  = smartDataManager;
            this.dataSourceMode    = dataSourceMode;
            this.messageBoxService = messageBoxService;
            this.windowManager     = windowManager;
            switch (dataSourceMode)
            {
            case SmartDataSourceMode.SD_SOURCE_EVENTS:
                DefinesItems = new ObservableCollection <SmartGenericJsonData>(smartDataProvider.GetEvents());
                break;

            case SmartDataSourceMode.SD_SOURCE_ACTIONS:
                DefinesItems = new ObservableCollection <SmartGenericJsonData>(smartDataProvider.GetActions());
                break;

            case SmartDataSourceMode.SD_SOURCE_TARGETS:
                DefinesItems = new ObservableCollection <SmartGenericJsonData>(smartDataProvider.GetTargets());
                break;

            default:
                DefinesItems = new ObservableCollection <SmartGenericJsonData>();
                break;
            }

            OnItemSelected = new AsyncAutoCommand <SmartGenericJsonData?>(ShowEditorWindow);
            CreateNew      = new AsyncAutoCommand(CreateNewItem);
            DeleteItem     = new DelegateCommand(DeleteSelectedItem);
            Save           = new DelegateCommand(() =>
            {
                taskRunner.ScheduleTask("Saving modified SmartData defines", SaveDataToFile);
            }, () => IsModified);
            SelectedItemIndex = -1;
            // history setup
            History                  = historyCreator();
            historyHandler           = new SmartDataListHistoryHandler(DefinesItems);
            UndoCommand              = new DelegateCommand(History.Undo, () => History.CanUndo);
            RedoCommand              = new DelegateCommand(History.Redo, () => History.CanRedo);
            History.PropertyChanged += (sender, args) =>
            {
                UndoCommand.RaiseCanExecuteChanged();
                RedoCommand.RaiseCanExecuteChanged();
                IsModified = !History.IsSaved;
                RaisePropertyChanged(nameof(IsModified));
            };
            History.AddHandler(historyHandler);
        }
コード例 #5
0
 public RowPickerViewModel(ViewModelBase baseViewModel,
                           ITaskRunner taskRunner,
                           ISolutionItemSqlGeneratorRegistry queryGeneratorRegistry,
                           IClipboardService clipboardService,
                           IWindowManager windowManager,
                           IEventAggregator eventAggregator,
                           ISolutionItemEditorRegistry solutionItemEditorRegistry,
                           ISessionService sessionService,
                           IMessageBoxService messageBoxService,
                           ISolutionTasksService solutionTasksService,
                           bool noSaveMode = false)
 {
     this.baseViewModel = baseViewModel;
     this.solutionItemEditorRegistry = solutionItemEditorRegistry;
     this.sessionService             = sessionService;
     this.messageBoxService          = messageBoxService;
     this.noSaveMode = noSaveMode;
     Watch(baseViewModel, o => o.IsModified, nameof(Title));
     ExecuteChangedCommand = noSaveMode ? AlwaysDisabledCommand.Command : new AsyncAutoCommand(async() =>
     {
         baseViewModel.Save.Execute(null);
         eventAggregator.GetEvent <DatabaseTableChanged>().Publish(baseViewModel.TableDefinition.TableName);
         await taskRunner.ScheduleTask("Update session", async() => await sessionService.UpdateQuery(baseViewModel));
         if (solutionTasksService.CanReloadRemotely)
         {
             await solutionTasksService.ReloadSolutionRemotelyTask(baseViewModel.SolutionItem);
         }
     });
     CopyCurrentSqlCommand = new AsyncAutoCommand(async() =>
     {
         await taskRunner.ScheduleTask("Generating SQL",
                                       async() => { clipboardService.SetText((await baseViewModel.GenerateQuery()).QueryString); });
     });
     GenerateCurrentSqlCommand = new AsyncAutoCommand(async() =>
     {
         var sql    = await baseViewModel.GenerateQuery();
         var item   = new MetaSolutionSQL(new JustQuerySolutionItem(sql.QueryString));
         var editor = solutionItemEditorRegistry.GetEditor(item);
         await windowManager.ShowDialog((IDialog)editor);
     });
     PickSelected = new AsyncAutoCommand(async() =>
     {
         await AskIfSave(false);
     });
     Cancel = new DelegateCommand(() =>
     {
         CloseCancel?.Invoke();
     });
     Accept = PickSelected;
 }
コード例 #6
0
        public TextDocumentViewModel(IWindowManager windowManager,
                                     INativeTextDocument nativeTextDocument)
        {
            Extension = "txt";
            Title     = "New file";
            document  = nativeTextDocument;

            SaveCommand = new AsyncAutoCommand(async() =>
            {
                var path = await windowManager.ShowSaveFileDialog($"{Extension} file|{Extension}|All files|*");
                if (path != null)
                {
                    await File.WriteAllTextAsync(path, document.ToString());
                }
            });
        }
コード例 #7
0
        public MpqSettingsViewModel(IMpqSettings mpqSettings,
                                    IWoWFilesVerifier verifier,
                                    IWindowManager windowManager,
                                    IMessageBoxService messageBoxService)
        {
            woWPath = mpqSettings.Path;

            Save = new DelegateCommand(() =>
            {
                mpqSettings.Path = woWPath;
                IsModified       = false;
                RaisePropertyChanged(nameof(IsModified));
            });

            PickFolder = new AsyncAutoCommand(async() =>
            {
                var folder = await windowManager.ShowFolderPickerDialog(woWPath ?? "");
                if (folder != null)
                {
                    if (verifier.VerifyFolder(folder) == WoWFilesType.Invalid)
                    {
                        await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                           .SetTitle("WoW Client Data")
                                                           .SetMainInstruction("Invalid WoW folder")
                                                           .SetContent(
                                                               "This doesn't look like a correct Wrath of The Lich King folder.\n\nSelect main game folder (wow.exe file must be there).\n\nOther WoW versions are not supported now.")
                                                           .WithOkButton(true)
                                                           .Build());
                    }
                    else
                    {
                        WoWPath = folder;
                    }
                }
            });
        }
コード例 #8
0
        public ConditionsEditorViewModel(
            IConditionsFactory conditionsFactory,
            IConditionDataManager conditionDataManager,
            IItemFromListProvider itemFromListProvider,
            IHistoryManager historyManager,
            IEnumerable <ICondition>?conditions,
            int conditionSourceType)
        {
            this.conditionsFactory    = conditionsFactory;
            this.conditionDataManager = conditionDataManager;
            this.HistoryManager       = historyManager;

            ConditionTypes = conditionDataManager
                             .GetConditionGroups()
                             .SelectMany(group => group.Members)
                             .Where(conditionDataManager.HasConditionData)
                             .Select(conditionDataManager.GetConditionData)
                             .ToList();

            if (conditions != null)
            {
                int previousElseGroup = -1;
                foreach (var c in conditions)
                {
                    var vm = conditionsFactory.Create(conditionSourceType, c);
                    if (vm == null)
                    {
                        continue;
                    }

                    if (c.ElseGroup != previousElseGroup && previousElseGroup != -1)
                    {
                        Conditions.Add(conditionsFactory.CreateOr(conditionSourceType));
                    }

                    previousElseGroup = c.ElseGroup;
                    Conditions.Add(vm);
                }
            }

            Accept      = new DelegateCommand(() => CloseOk?.Invoke());
            Cancel      = new DelegateCommand(() => CloseCancel?.Invoke());
            PickCommand = new AsyncAutoCommand <ParameterValueHolder <long> >(async prh =>
            {
                if (!prh.HasItems)
                {
                    return;
                }

                var newItem = await itemFromListProvider.GetItemFromList(prh.Parameter.Items, prh.Parameter is FlagParameter, prh.Value);
                if (newItem.HasValue)
                {
                    prh.Value = newItem.Value;
                }
            });
            AddItemCommand = new DelegateCommand(() =>
            {
                int index = Conditions.Count;
                if (SelectedCondition != null)
                {
                    index = Conditions.IndexOf(SelectedCondition) + 1;
                }
                index = Math.Clamp(index, 0, Conditions.Count);

                Conditions.Insert(index, conditionsFactory.Create(conditionSourceType, 0) ?? conditionsFactory.CreateOr(conditionSourceType));
            });
            RemoveItemCommand = new DelegateCommand(() =>
            {
                if (SelectedCondition == null)
                {
                    return;
                }

                int indexOf = Conditions.IndexOf(SelectedCondition);
                if (indexOf != -1)
                {
                    Conditions.RemoveAt(indexOf);
                    if (indexOf - 1 >= 0 && Conditions.Count > 0)
                    {
                        SelectedCondition = Conditions[indexOf - 1];
                    }
                    else if (Conditions.Count > 0)
                    {
                        SelectedCondition = Conditions[indexOf];
                    }
                }
            }, () => SelectedCondition != null).ObservesProperty(() => SelectedCondition);
            CopyCommand = new DelegateCommand(() =>
            {
                if (SelectedCondition != null)
                {
                    Clipboard = SelectedCondition?.ToCondition(0);
                }
            }, () => SelectedCondition != null).ObservesProperty(() => SelectedCondition);
            CutCommand = new DelegateCommand(() =>
            {
                if (SelectedCondition != null)
                {
                    Clipboard = SelectedCondition?.ToCondition(0);
                    Conditions.Remove(SelectedCondition !);
                    SelectedCondition = null;
                }
            }, () => SelectedCondition != null).ObservesProperty(() => SelectedCondition);
            PasteCommand = new DelegateCommand(() =>
            {
                if (clipboard != null)
                {
                    int indexOf = Conditions.Count;
                    if (SelectedCondition != null)
                    {
                        indexOf = Conditions.IndexOf(SelectedCondition) + 1;
                    }
                    var item = conditionsFactory.Create(conditionSourceType, clipboard);
                    if (item != null)
                    {
                        Conditions.Insert(indexOf, item);
                    }
                }
            }, () => Clipboard != null).ObservesProperty(() => Clipboard);

            UndoCommand =
                new DelegateCommand(HistoryManager.Undo, () => HistoryManager.CanUndo).ObservesProperty(() =>
                                                                                                        HistoryManager.CanUndo);
            RedoCommand =
                new DelegateCommand(HistoryManager.Redo, () => HistoryManager.CanRedo).ObservesProperty(() =>
                                                                                                        HistoryManager.CanRedo);

            Watch(this, t => t.SelectedCondition, nameof(SelectedConditionsType));

            historyHandler = AutoDispose(new ConditionsEditorHistoryHandler(this, conditionsFactory));
            HistoryManager.AddHandler(historyHandler);
        }
コード例 #9
0
        public PacketDocumentViewModel(PacketDocumentSolutionItem solutionItem,
                                       IMainThread mainThread,
                                       MostRecentlySearchedService mostRecentlySearchedService,
                                       IDatabaseProvider databaseProvider,
                                       Func <INativeTextDocument> nativeTextDocumentCreator,
                                       IMessageBoxService messageBoxService,
                                       IPacketFilteringService filteringService,
                                       IDocumentManager documentManager,
                                       ITextDocumentService textDocumentService,
                                       IWindowManager windowManager,
                                       IPacketViewerSettings packetSettings,
                                       IEnumerable <IPacketDumperProvider> dumperProviders,
                                       IInputBoxService inputBoxService,
                                       IHistoryManager history,
                                       IPacketFilterDialogService filterDialogService,
                                       IActionReactionProcessorCreator actionReactionProcessorCreator,
                                       IRelatedPacketsFinder relatedPacketsFinder,
                                       ITeachingTipService teachingTipService,
                                       PacketDocumentSolutionNameProvider solutionNameProvider,
                                       ISniffLoader sniffLoader,
                                       ISpellStore spellStore,
                                       PrettyFlagParameter prettyFlagParameter,
                                       Func <IUpdateFieldsHistory> historyCreator)
        {
            this.solutionItem      = solutionItem;
            this.mainThread        = mainThread;
            this.messageBoxService = messageBoxService;
            this.filteringService  = filteringService;
            this.actionReactionProcessorCreator = actionReactionProcessorCreator;
            this.relatedPacketsFinder           = relatedPacketsFinder;
            this.sniffLoader = sniffLoader;
            History          = history;
            history.LimitStack(20);
            packetViewModelCreator = new PacketViewModelFactory(databaseProvider, spellStore);
            MostRecentlySearched   = mostRecentlySearchedService.MostRecentlySearched;
            Title                 = solutionNameProvider.GetName(this.solutionItem);
            SolutionItem          = solutionItem;
            FilterText            = nativeTextDocumentCreator();
            SelectedPacketPreview = nativeTextDocumentCreator();
            SelectedPacketPreview.DisableUndo();
            Watch(this, t => t.FilteringProgress, nameof(ProgressUnknown));

            AutoDispose(history.AddHandler(new SelectedPacketHistory(this)));

            filteredPackets    = visiblePackets = AllPackets;
            ApplyFilterCommand = new AsyncCommand(async() =>
            {
                if (inApplyFilterCommand)
                {
                    return;
                }

                inApplyFilterCommand     = true;
                MostRecentlySearchedItem = FilterText.ToString();
                inApplyFilterCommand     = false;

                if (!string.IsNullOrEmpty(FilterText.ToString()))
                {
                    mostRecentlySearchedService.Add(FilterText.ToString());
                }

                if (currentActionToken != filteringToken)
                {
                    throw new Exception("Invalid concurrent access!");
                }
                filteringToken?.Cancel();
                filteringToken     = null;
                currentActionToken = null;
                await FilterPackets(FilterText.ToString());
            });

            SaveToFileCommand = new AsyncCommand(async() =>
            {
                var path = await windowManager.ShowSaveFileDialog("Text file|txt");
                if (path == null)
                {
                    return;
                }

                LoadingInProgress   = true;
                FilteringInProgress = true;
                try
                {
                    await using StreamWriter writer = File.CreateText(path);
                    int i     = 0;
                    int count = FilteredPackets.Count;
                    foreach (var packet in FilteredPackets)
                    {
                        await writer.WriteLineAsync(packet.Text);
                        if ((i % 100) == 0)
                        {
                            Report(i * 1.0f / count);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    await this.messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                            .SetTitle("Fatal error")
                                                            .SetMainInstruction("Fatal error during saving file")
                                                            .SetContent(e.Message)
                                                            .WithOkButton(false)
                                                            .Build());
                }
                LoadingInProgress   = false;
                FilteringInProgress = false;
            });

            OpenHelpCommand = new DelegateCommand(() => windowManager.OpenUrl("https://github.com/BAndysc/WoWDatabaseEditor/wiki/Packet-Viewer"));

            On(() => SelectedPacket, doc =>
            {
                if (doc != null)
                {
                    SelectedPacketPreview.FromString(doc.Text);
                }
            });

            On(() => SplitUpdate, _ =>
            {
                SplitPacketsIfNeededAsync().Wait();
                ((ICommand)ApplyFilterCommand).Execute(null);
            });

            On(() => HidePlayerMove, _ =>
            {
                ((ICommand)ApplyFilterCommand).Execute(null);
            });

            On(() => DisableFilters, _ =>
            {
                ((ICommand)ApplyFilterCommand).Execute(null);
            });

            foreach (var dumper in dumperProviders)
            {
                Processors.Add(new(dumper));
            }

            QuickRunProcessor = new AsyncAutoCommand <ProcessorViewModel>(async(processor) =>
            {
                LoadingInProgress   = true;
                FilteringInProgress = true;
                try
                {
                    var tokenSource = new CancellationTokenSource();
                    AssertNoOnGoingTask();
                    currentActionToken = tokenSource;

                    var output = await RunProcessorsThreaded(new List <ProcessorViewModel>()
                    {
                        processor
                    }, tokenSource.Token).ConfigureAwait(true);

                    if (output != null && !tokenSource.IsCancellationRequested)
                    {
                        documentManager.OpenDocument(textDocumentService.CreateDocument($"{processor.Name} ({Title})", output, processor.Extension, true));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                       .SetIcon(MessageBoxIcon.Error)
                                                       .SetTitle("Fatal error")
                                                       .SetMainInstruction("Fatal error during processing")
                                                       .SetContent(
                                                           "Sorry, fatal error occured, this is probably a bug in processors, please report it in github\n\n" + e)
                                                       .WithOkButton(true)
                                                       .Build());
                }
                LoadingInProgress   = false;
                FilteringInProgress = false;
                currentActionToken  = null;
            });

            RunProcessors = new AsyncAutoCommand(async() =>
            {
                var processors = Processors.Where(s => s.IsChecked).ToList();
                if (processors.Count == 0)
                {
                    return;
                }

                LoadingInProgress   = true;
                FilteringInProgress = true;
                try
                {
                    var tokenSource = new CancellationTokenSource();
                    AssertNoOnGoingTask();
                    currentActionToken = tokenSource;

                    var output = await RunProcessorsThreaded(processors, tokenSource.Token).ConfigureAwait(true);

                    if (output != null && !tokenSource.IsCancellationRequested)
                    {
                        var extension = processors.Select(p => p.Extension).Distinct().Count() == 1
                            ? processors[0].Extension
                            : "txt";
                        documentManager.OpenDocument(textDocumentService.CreateDocument($"{processors[0].Name} ({Title})", output, extension, true));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                       .SetIcon(MessageBoxIcon.Error)
                                                       .SetTitle("Fatal error")
                                                       .SetMainInstruction("Fatal error during processing")
                                                       .SetContent(
                                                           "Sorry, fatal error occured, this is probably a bug in processors, please report it in github\n\n" + e)
                                                       .WithOkButton(true)
                                                       .Build());
                }
                LoadingInProgress   = false;
                FilteringInProgress = false;
                currentActionToken  = null;
            }, () => Processors.Any(c => c.IsChecked));

            foreach (var proc in Processors)
            {
                AutoDispose(proc.ToObservable(p => p.IsChecked)
                            .SubscribeAction(_ => RunProcessors.RaiseCanExecuteChanged()));
            }

            UndoCommand              = new DelegateCommand(history.Undo, () => history.CanUndo);
            RedoCommand              = new DelegateCommand(history.Redo, () => history.CanRedo);
            History.PropertyChanged += (_, _) =>
            {
                UndoCommand.RaiseCanExecuteChanged();
                RedoCommand.RaiseCanExecuteChanged();
            };

            IEnumerable <int> GetFindEnumerator(int start, int count, int direction, bool wrap)
            {
                for (int i = start + direction; i >= 0 && i < count; i += direction)
                {
                    yield return(i);
                }

                if (wrap)
                {
                    if (direction > 0)
                    {
                        for (int i = 0; i < start; ++i)
                        {
                            yield return(i);
                        }
                    }
                    else
                    {
                        for (int i = count - 1; i > start; --i)
                        {
                            yield return(i);
                        }
                    }
                }
            }

            async Task Find(string searchText, int start, int direction)
            {
                var count         = VisiblePackets.Count;
                var searchToLower = searchText.ToLower();

                foreach (var i in GetFindEnumerator(start, count, direction, true))
                {
                    if (VisiblePackets[i].Text.Contains(searchToLower, StringComparison.InvariantCultureIgnoreCase))
                    {
                        SelectedPacket = VisiblePackets[i];
                        return;
                    }
                }

                await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                   .SetTitle("Find")
                                                   .SetMainInstruction("Not found")
                                                   .SetContent("Cannot find text: " + searchText)
                                                   .WithOkButton(true)
                                                   .Build());
            }

            ToggleFindCommand   = new DelegateCommand(() => FindPanelEnabled = !FindPanelEnabled);
            CloseFindCommand    = new DelegateCommand(() => FindPanelEnabled = false);
            FindPreviousCommand = new AsyncAutoCommand <string>(async searchText =>
            {
                var start = SelectedPacket != null ? VisiblePackets.IndexOf(SelectedPacket) : 0;
                await Find(searchText, start, -1);
            }, str => str is string s && !string.IsNullOrEmpty(s));
            FindNextCommand = new AsyncAutoCommand <string>(async searchText =>
            {
                var start = SelectedPacket != null ? VisiblePackets.IndexOf(SelectedPacket) : 0;
                await Find(searchText, start, 1);
            }, str => str is string s && !string.IsNullOrEmpty(s));

            FindRelatedPacketsCommands = new AsyncAutoCommand(async() =>
            {
                if (selectedPacket == null)
                {
                    return;
                }

                if (!await EnsureSplitOrDismiss())
                {
                    return;
                }

                FilteringInProgress = true;
                FilteringProgress   = -1;
                var tokenSource     = new CancellationTokenSource();
                AssertNoOnGoingTask();
                currentActionToken        = tokenSource;
                IFilterData?newFilterData = await GetRelatedFilters(selectedPacket.Packet.BaseData.Number, tokenSource.Token);
                FilteringInProgress       = false;
                currentActionToken        = null;

                if (newFilterData == null)
                {
                    return;
                }

                if (!FilterData.IsEmpty)
                {
                    if (await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                           .SetTitle("Find related packets")
                                                           .SetMainInstruction("Your current filter data is not empty")
                                                           .SetContent("Do you want to override current filter data?")
                                                           .WithButton("Override", true)
                                                           .WithButton("Merge", false)
                                                           .Build()))
                    {
                        FilterData = newFilterData;
                    }
                    else
                    {
                        FilterData.SetMinMax(Min(FilterData.MinPacketNumber, newFilterData.MinPacketNumber),
                                             Max(FilterData.MaxPacketNumber, newFilterData.MaxPacketNumber));
                        if (newFilterData.IncludedGuids != null)
                        {
                            foreach (var guid in newFilterData.IncludedGuids)
                            {
                                FilterData.IncludeGuid(guid);
                            }
                        }
                        if (newFilterData.ForceIncludePacketNumbers != null)
                        {
                            foreach (var packet in newFilterData.ForceIncludePacketNumbers)
                            {
                                FilterData.IncludePacketNumber(packet);
                            }
                        }
                    }
                }
                else
                {
                    FilterData = newFilterData;
                }

                await ApplyFilterCommand.ExecuteAsync();
            });

            ExcludeEntryCommand = new AsyncAutoCommand <PacketViewModel?>(async vm =>
            {
                if (vm == null || vm.Entry == 0)
                {
                    return;
                }

                FilterData.ExcludeEntry(vm.Entry);
                await ApplyFilterCommand.ExecuteAsync();
            }, vm => vm is PacketViewModel pvm && pvm.Entry != 0);

            IncludeEntryCommand = new AsyncAutoCommand <PacketViewModel?>(async vm =>
            {
                if (vm == null || vm.Entry == 0)
                {
                    return;
                }

                FilterData.IncludeEntry(vm.Entry);
                await ApplyFilterCommand.ExecuteAsync();
            }, vm => vm is PacketViewModel pvm && pvm.Entry != 0);

            ExcludeGuidCommand = new AsyncAutoCommand <PacketViewModel?>(async vm =>
            {
                if (vm == null || vm.MainActor == null)
                {
                    return;
                }

                FilterData.ExcludeGuid(vm.MainActor);
                await ApplyFilterCommand.ExecuteAsync();
            }, vm => vm is PacketViewModel pvm && pvm.MainActor != null);

            IncludeGuidCommand = new AsyncAutoCommand <PacketViewModel?>(async vm =>
            {
                if (vm == null || vm.MainActor == null)
                {
                    return;
                }

                FilterData.IncludeGuid(vm.MainActor);
                await ApplyFilterCommand.ExecuteAsync();
            }, vm => vm is PacketViewModel pvm && pvm.MainActor != null);

            ExcludeOpcodeCommand = new AsyncAutoCommand <PacketViewModel?>(async vm =>
            {
                if (vm == null)
                {
                    return;
                }

                FilterData.ExcludeOpcode(vm.Opcode);
                await ApplyFilterCommand.ExecuteAsync();
            }, vm => vm != null);

            IncludeOpcodeCommand = new AsyncAutoCommand <PacketViewModel?>(async vm =>
            {
                if (vm == null)
                {
                    return;
                }

                FilterData.IncludeOpcode(vm.Opcode);
                await ApplyFilterCommand.ExecuteAsync();
            }, vm => vm != null);

            AutoDispose(this.ToObservable(o => o.SelectedPacket).SubscribeAction(_ =>
            {
                ExcludeEntryCommand.RaiseCanExecuteChanged();
                IncludeEntryCommand.RaiseCanExecuteChanged();
                ExcludeGuidCommand.RaiseCanExecuteChanged();
                IncludeGuidCommand.RaiseCanExecuteChanged();
                ExcludeOpcodeCommand.RaiseCanExecuteChanged();
                IncludeOpcodeCommand.RaiseCanExecuteChanged();
            }));

            ExplainSelectedPacketCommand = new AsyncAutoCommand(async() =>
            {
                if (!reasonPanelVisibility || actionReactionProcessor == null)
                {
                    return;
                }
                if (selectedPacket == null)
                {
                    return;
                }

                DetectedActions.Clear();
                var detected = actionReactionProcessor.GetAllActions(selectedPacket.Id);
                if (detected != null)
                {
                    DetectedActions.AddRange(detected.Select(s => new DetectedActionViewModel(s)));
                }

                DetectedEvents.Clear();
                var events = actionReactionProcessor.GetAllEvents(selectedPacket.Id);
                if (events != null)
                {
                    DetectedEvents.AddRange(events.Select(s => new DetectedEventViewModel(s)));
                }

                var reasons = actionReactionProcessor.GetPossibleEventsForAction(selectedPacket.Packet.BaseData);
                Predictions.Clear();
                foreach (var reason in reasons)
                {
                    Predictions.Add(new ActionReasonPredictionViewModel(selectedPacket.Packet.BaseData, reason.rate.Value, reason.rate.Explain, reason.@event));
                }
                PossibleActions.Clear();
                var actions = actionReactionProcessor.GetPossibleActionsForEvent(selectedPacket.Packet.BaseData.Number);
                foreach (var action in actions)
                {
                    var actionHappened = actionReactionProcessor.GetAction(action.packetId);
                    if (actionHappened == null)
                    {
                        continue;
                    }
                    PossibleActions.Add(new PossibleActionViewModel(selectedPacket.Packet.BaseData, action.chance, "", actionHappened.Value));
                }
            }, () => ReasonPanelVisibility);

            On(() => ReasonPanelVisibility, isVisible =>
            {
                if (!isVisible)
                {
                    return;
                }
                ApplyFilterCommand.ExecuteAsync().ContinueWith(_ =>
                {
                    ExplainSelectedPacketCommand.Execute(null);
                }, TaskContinuationOptions.NotOnCanceled | TaskContinuationOptions.NotOnFaulted).ListenErrors();
            });

            AutoDispose(this.ToObservable(o => o.SelectedPacket)
                        .CombineLatest(this.ToObservable(o => o.ReasonPanelVisibility))
                        .SubscribeAction(
                            _ =>
            {
                ExplainSelectedPacketCommand.Execute(null);
            }));

            OpenFilterDialogCommand = new AsyncAutoCommand(async() =>
            {
                var newData = await filterDialogService.OpenFilterDialog(FilterData);
                if (newData != null)
                {
                    FilterData = newData;
                    await ApplyFilterCommand.ExecuteAsync();
                }
            });

            JumpToPacketCommand = new DelegateCommand <int?>(packetId =>
            {
                if (!packetId.HasValue)
                {
                    return;
                }
                var packet = filteredPackets.FirstOrDefault(p => p.Id == packetId.Value);
                if (packet != null)
                {
                    SelectedPacket = packet;
                }
            });

            GoToPacketCommand = new AsyncAutoCommand(async() =>
            {
                var min    = filteredPackets[0].Id;
                var max    = filteredPackets[^ 1].Id;
コード例 #10
0
        public WizardStyleViewModelBase(
            IMessageBoxService messageBoxService,
            ICoreSourceSettings coreSourceSettings,
            ISourceSqlUpdateService sqlUpdateService,
            IAuthMySqlExecutor authExecutor,
            IMySqlExecutor worldExecutor,
            IWindowManager windowManager,
            ITaskRunner taskRunner,
            IStatusBar statusBar,
            INativeTextDocument resultCode)
        {
            ResultCode       = resultCode;
            CoreSourceFolder = coreSourceSettings.CurrentCorePath;
            if (!string.IsNullOrEmpty(coreSourceSettings.CurrentCorePath))
            {
                Dispatcher.UIThread.Post(() => WizardStep++);
            }

            CommandPreviousStep = new DelegateCommand(() => WizardStep--, () => !IsLoading && WizardStep > 0)
                                  .ObservesProperty(() => IsLoading)
                                  .ObservesProperty(() => WizardStep);

            CommandNextStep = new DelegateCommand(() => WizardStep++, () => !IsLoading && WizardStep < TotalSteps - 1)
                              .ObservesProperty(() => IsLoading)
                              .ObservesProperty(() => WizardStep);

            PickCoreSourceFolder = new AsyncAutoCommand(async() =>
            {
                var selectedPath = await windowManager.ShowFolderPickerDialog(coreSourceFolder);
                if (selectedPath != null)
                {
                    if (!coreSourceSettings.SetCorePath(selectedPath))
                    {
                        await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                           .SetTitle("Invalid folder")
                                                           .SetMainInstruction("Invalid wow source folder")
                                                           .SetContent(
                                                               "It looks like it is not an valid wow server source folder.\n\nThe folder should contain src/ and sql/ subfolders")
                                                           .WithOkButton(true)
                                                           .Build());
                    }
                    CoreSourceFolder = coreSourceSettings.CurrentCorePath;
                }
            });

            ExecuteSqlCommand = new AsyncAutoCommand(async() =>
            {
                var(auth, world) = GenerateSql();
                try
                {
                    await taskRunner.ScheduleTask("Executing commands update", async() =>
                    {
                        statusBar.PublishNotification(new PlainNotification(NotificationType.Info, "Executing query"));
                        if (auth != null)
                        {
                            if (authExecutor.IsConnected)
                            {
                                await authExecutor.ExecuteSql(auth);
                            }
                            else
                            {
                                await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                                   .SetTitle("Auth database not connected")
                                                                   .SetIcon(MessageBoxIcon.Warning)
                                                                   .SetMainInstruction("Auth database not connected")
                                                                   .SetContent(
                                                                       "You are trying to execute auth query, but auth database is not connected.\n\nEnsure you have correct auth database data in settings.")
                                                                   .WithOkButton(true)
                                                                   .Build());
                            }
                        }

                        if (world != null)
                        {
                            if (worldExecutor.IsConnected)
                            {
                                await worldExecutor.ExecuteSql(world);
                            }
                            else
                            {
                                await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                                   .SetTitle("World database not connected")
                                                                   .SetIcon(MessageBoxIcon.Warning)
                                                                   .SetMainInstruction("World database not connected")
                                                                   .SetContent(
                                                                       "You are trying to execute world query, but world database is not connected.\n\nEnsure you have correct world database data in settings.")
                                                                   .WithOkButton(true)
                                                                   .Build());
                            }
                        }

                        statusBar.PublishNotification(new PlainNotification(NotificationType.Success,
                                                                            "Executed query"));
                    });
                }
                catch (Exception)
                {
                    statusBar.PublishNotification(new PlainNotification(NotificationType.Error, "Error while executing query. Check Database Query Debug window"));
                }
            }, _ => worldExecutor.IsConnected || authExecutor.IsConnected);

            SaveSqlCommand = new AsyncAutoCommand(async() =>
            {
                var(auth, world) = GenerateSql();

                if (auth != null)
                {
                    sqlUpdateService.SaveAuthUpdate(SqlSuffixName, auth);
                }

                if (world != null)
                {
                    sqlUpdateService.SaveWorldUpdate(SqlSuffixName, world);
                }

                if (auth != null || world != null)
                {
                    await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                       .SetTitle("Done!")
                                                       .SetContent("SQL files saved to sql/updates/")
                                                       .SetIcon(MessageBoxIcon.Information)
                                                       .WithOkButton(true)
                                                       .Build());
                }
            });
        }
コード例 #11
0
        public PacketFilterDialogViewModel(IClipboardService clipboardService,
                                           IReadOnlyFilterData?filterData)
        {
            this.clipboardService = clipboardService;
            Accept = new DelegateCommand(() => CloseOk?.Invoke());
            Cancel = new DelegateCommand(() => CloseCancel?.Invoke());

            ClearFiltersCommand = new AsyncAutoCommand(async() =>
            {
                ExcludedEntries = "";
                IncludedEntries = "";
                ExcludedOpcodes = "";
                IncludedOpcodes = "";
                ExcludedGuids.Clear();
                IncludedGuids.Clear();
                CommaSeparatedPackets = "";
                HasMaxPacketNumber    = false;
                HasMinPacketNumber    = false;
                MinPacketNumber       = 0;
                MaxPacketNumber       = 0;
            });
            CopyFiltersCommand = new AsyncAutoCommand(async() =>
            {
                var data = new SerializedClipboardData()
                {
                    ExcludedEntries      = GenerateList(excludedEntries, s => uint.TryParse(s, out _), uint.Parse),
                    IncludedEntries      = GenerateList(includedOpcodes, s => uint.TryParse(s, out _), uint.Parse),
                    ExcludedGuids        = ExcludedGuids.Count == 0 ? null : ExcludedGuids.Select(s => s.ToHexWithTypeString()).ToList(),
                    IncludedGuids        = IncludedGuids.Count == 0 ? null : IncludedGuids.Select(s => s.ToHexWithTypeString()).ToList(),
                    ExcludedOpcodes      = GenerateList(excludedOpcodes, _ => true, s => s.ToUpper()),
                    IncludedOpcodes      = GenerateList(includedOpcodes, _ => true, s => s.ToUpper()),
                    ForceIncludedNumbers = GenerateList(commaSeparatedPackets, s => int.TryParse(s, out var x) && x >= 0, int.Parse),
                    MinPacket            = HasMinPacketNumber ? MinPacketNumber : null,
                    MaxPacket            = HasMaxPacketNumber ? MaxPacketNumber : null,
                };
                var serialized = JsonConvert.SerializeObject(data, Formatting.Indented, new JsonSerializerSettings()
                {
                    NullValueHandling = NullValueHandling.Ignore
                });
                clipboardService.SetText(serialized);
            });
            PasteFiltersCommand = new AsyncAutoCommand(async() =>
            {
                var text = await clipboardService.GetText();
                if (string.IsNullOrEmpty(text))
                {
                    return;
                }

                SerializedClipboardData?serialized = null;
                try
                {
                    serialized = JsonConvert.DeserializeObject <SerializedClipboardData>(text);
                }
                catch (Exception _)
                {
                    // ignored
                }

                if (!serialized.HasValue)
                {
                    return;
                }

                HasMinPacketNumber = serialized.Value.MinPacket.HasValue;
                HasMaxPacketNumber = serialized.Value.MaxPacket.HasValue;
                MinPacketNumber    = serialized.Value.MinPacket ?? 0;
                MaxPacketNumber    = serialized.Value.MaxPacket ?? 0;

                if (serialized.Value.ExcludedEntries != null)
                {
                    ExcludedEntries = string.Join(", ", serialized.Value.ExcludedEntries);
                }
                if (serialized.Value.IncludedEntries != null)
                {
                    IncludedEntries = string.Join(", ", serialized.Value.IncludedEntries);
                }
                if (serialized.Value.ExcludedGuids != null)
                {
                    ExcludedGuids.AddRange(serialized.Value.ExcludedGuids.StringToGuids());
                }
                if (serialized.Value.IncludedGuids != null)
                {
                    IncludedGuids.AddRange(serialized.Value.IncludedGuids.StringToGuids());
                }
                if (serialized.Value.ExcludedOpcodes != null)
                {
                    ExcludedOpcodes = string.Join(", ", serialized.Value.ExcludedOpcodes);
                }
                if (serialized.Value.IncludedOpcodes != null)
                {
                    IncludedOpcodes = string.Join(", ", serialized.Value.IncludedOpcodes);
                }
                if (serialized.Value.ForceIncludedNumbers != null)
                {
                    CommaSeparatedPackets = string.Join(", ", serialized.Value.ForceIncludedNumbers);
                }
            });

            if (filterData != null)
            {
                HasMinPacketNumber = filterData.MinPacketNumber.HasValue;
                HasMaxPacketNumber = filterData.MaxPacketNumber.HasValue;
                MinPacketNumber    = filterData.MinPacketNumber ?? 0;
                MaxPacketNumber    = filterData.MaxPacketNumber ?? 0;

                if (filterData.ExcludedEntries != null)
                {
                    ExcludedEntries = string.Join(", ", filterData.ExcludedEntries);
                }
                if (filterData.IncludedEntries != null)
                {
                    IncludedEntries = string.Join(", ", filterData.IncludedEntries);
                }
                if (filterData.ExcludedGuids != null)
                {
                    ExcludedGuids.AddRange(filterData.ExcludedGuids);
                }
                if (filterData.IncludedGuids != null)
                {
                    IncludedGuids.AddRange(filterData.IncludedGuids);
                }
                if (filterData.ExcludedOpcodes != null)
                {
                    ExcludedOpcodes = string.Join(", ", filterData.ExcludedOpcodes);
                }
                if (filterData.IncludedOpcodes != null)
                {
                    IncludedOpcodes = string.Join(", ", filterData.IncludedOpcodes);
                }
                if (filterData.ForceIncludePacketNumbers != null)
                {
                    CommaSeparatedPackets = string.Join(", ", filterData.ForceIncludePacketNumbers);
                }
            }

            DeleteIncludedGuid = new DelegateCommand <UniversalGuid?>(guid =>
            {
                if (guid != null)
                {
                    IncludedGuids.Remove(guid);
                }
            });

            DeleteExcludedGuid = new DelegateCommand <UniversalGuid?>(guid =>
            {
                if (guid != null)
                {
                    ExcludedGuids.Remove(guid);
                }
            });

            AutoDispose(this.ToObservable(o => o.ExcludedEntries).SubscribeAction(_ => RaisePropertyChanged(nameof(EntriesHeader))));
            AutoDispose(this.ToObservable(o => o.IncludedEntries).SubscribeAction(_ => RaisePropertyChanged(nameof(EntriesHeader))));
            AutoDispose(ExcludedGuids.ToCountChangedObservable().SubscribeAction(_ => RaisePropertyChanged(nameof(GuidsHeader))));
            AutoDispose(IncludedGuids.ToCountChangedObservable().SubscribeAction(_ => RaisePropertyChanged(nameof(GuidsHeader))));
            AutoDispose(this.ToObservable(o => o.ExcludedOpcodes).SubscribeAction(_ => RaisePropertyChanged(nameof(OpcodesHeader))));
            AutoDispose(this.ToObservable(o => o.IncludedOpcodes).SubscribeAction(_ => RaisePropertyChanged(nameof(OpcodesHeader))));
        }
コード例 #12
0
        public TextDocumentViewModel(IWindowManager windowManager,
                                     ITaskRunner taskRunner,
                                     IStatusBar statusBar,
                                     IMySqlExecutor mySqlExecutor,
                                     IDatabaseProvider databaseProvider,
                                     INativeTextDocument nativeTextDocument,
                                     IQueryParserService queryParserService,
                                     ISessionService sessionService,
                                     IMessageBoxService messageBoxService)
        {
            Extension      = "txt";
            Title          = "New file";
            this.statusBar = statusBar;
            document       = nativeTextDocument;

            SaveCommand = new AsyncAutoCommand(async() =>
            {
                var path = await windowManager.ShowSaveFileDialog($"{Extension} file|{Extension}|All files|*");
                if (path != null)
                {
                    await File.WriteAllTextAsync(path, document.ToString());
                }
            });
            ExecuteSqlSaveSession = new DelegateCommand(() =>
            {
                taskRunner.ScheduleTask("Executing query",
                                        () => WrapStatusbar(async() =>
                {
                    var query = Document.ToString();
                    IList <ISolutionItem>?solutionItems = null;
                    IList <string>?errors = null;
                    if (inspectQuery && sessionService.IsOpened && !sessionService.IsPaused)
                    {
                        (solutionItems, errors) = await queryParserService.GenerateItemsForQuery(query);
                    }

                    await mySqlExecutor.ExecuteSql(query);

                    if (solutionItems != null)
                    {
                        foreach (var item in solutionItems)
                        {
                            await sessionService.UpdateQuery(item);
                        }
                        if (errors !.Count > 0)
                        {
                            await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                               .SetTitle("Apply query")
                                                               .SetMainInstruction("Some queries couldn't be transformed into session items")
                                                               .SetContent("Details:\n\n" + string.Join("\n", errors.Select(s => "  - " + s)))
                                                               .WithOkButton(true)
                                                               .Build());
                        }
                    }
                }));
            }, () => databaseProvider.IsConnected);
            ExecuteSql = new DelegateCommand(() =>
            {
                taskRunner.ScheduleTask("Executing query",
                                        () => WrapStatusbar(() => mySqlExecutor.ExecuteSql(Document.ToString())));
            }, () => databaseProvider.IsConnected);
        }
コード例 #13
0
    public async Task Find(IFindAnywhereResultContext resultContext, IReadOnlyList <string> parameterNames, long parameterValue, CancellationToken cancellationToken)
    {
        var command = new AsyncAutoCommand(() => messageBoxService.Value.ShowDialog(new MessageBoxFactory <bool>()
                                                                                    .SetTitle("DBC entry")
                                                                                    .SetMainInstruction("This is a DBC spell")
                                                                                    .SetContent("You cannot open it, it is just an info for you that such spell exists")
                                                                                    .WithButton("Understood!", true, true, true)
                                                                                    .Build()));

        var spellService = spellServiceLazy.Value;
        var spellStore   = spellStoreLazy.Value;
        var mainThread   = mainThreadLazy.Value;

        void AddThing(uint spell, string name, string description, ImageUri icon)
        {
            mainThread.Dispatch(() =>
            {
                resultContext.AddResult(new FindAnywhereResult(icon,
                                                               name + " (" + spell + ")",
                                                               description,
                                                               null,
                                                               command));
            });
        }

        if (parameterNames.IndexOf("SpellParameter") != -1)
        {
            if (spellStore.HasSpell((uint)parameterValue))
            {
                AddThing((uint)parameterValue, spellStore.GetName((uint)parameterValue) ?? "(unknown)", spellService.GetDescription((uint)parameterValue) ?? "Spell in DBC", new ImageUri("Icons/document_instance_template_big.png"));
            }
        }

        await Task.Run(() =>
        {
            foreach (var(spell, name) in spellStore.SpellsWithName)
            {
                if (cancellationToken.IsCancellationRequested)
                {
                    return;
                }

                for (int i = 0; i < spellService.GetSpellEffectsCount(spell); ++i)
                {
                    var type = spellService.GetSpellEffectType(spell, i);
                    if (type == SpellEffectType.SendEvent)
                    {
                        if (parameterNames.IndexOf("EventScriptParameter") != -1)
                        {
                            var @event = spellService.GetSpellEffectMiscValueA(spell, i);
                            if (@event == parameterValue)
                            {
                                AddThing(spell, name, $"Effect {i}: SPELL_EFFECT_SEND_EVENT with event {@event}", new ImageUri("Icons/document_instance_template_big.png"));
                            }
                        }
                    }
                    else if (type == SpellEffectType.Summon)
                    {
                        if (parameterNames.IndexOf("CreatureParameter") != -1)
                        {
                            var entry = spellService.GetSpellEffectMiscValueA(spell, i);
                            if (entry == parameterValue)
                            {
                                AddThing(spell, name, $"Effect {i}: SPELL_EFFECT_SUMMON with npc {entry}", new ImageUri("Icons/document_instance_template_big.png"));
                            }
                        }
                    }

                    var triggerSpell = spellService.GetSpellEffectTriggerSpell(spell, i);
                    if (triggerSpell == parameterValue && parameterNames.IndexOf("SpellParameter") != -1)
                    {
                        AddThing(spell, name, $"Effect {i}: Trigger spell {triggerSpell}", new ImageUri("Icons/document_spell_linked_big.png"));
                    }
                }
            }
        }, cancellationToken);
    }
コード例 #14
0
        public SmartScriptEditorViewModel(IHistoryManager history,
                                          IDatabaseProvider database,
                                          IEventAggregator eventAggregator,
                                          ISmartDataManager smartDataManager,
                                          ISmartFactory smartFactory,
                                          IItemFromListProvider itemFromListProvider,
                                          ISmartTypeListProvider smartTypeListProvider,
                                          IStatusBar statusbar,
                                          ISolutionItemNameRegistry itemNameRegistry)
        {
            this.history               = history;
            this.database              = database;
            this.smartDataManager      = smartDataManager;
            this.smartFactory          = smartFactory;
            this.itemFromListProvider  = itemFromListProvider;
            this.smartTypeListProvider = smartTypeListProvider;
            this.statusbar             = statusbar;
            this.itemNameRegistry      = itemNameRegistry;

            EditEvent       = new DelegateCommand(EditEventCommand);
            DeselectActions = new DelegateCommand(() =>
            {
                foreach (var e in Events)
                {
                    if (!e.IsSelected)
                    {
                        foreach (var a in e.Actions)
                        {
                            a.IsSelected = false;
                        }
                    }
                }
            });
            DeselectAll = new DelegateCommand(() =>
            {
                foreach (var e in Events)
                {
                    foreach (var a in e.Actions)
                    {
                        a.IsSelected = false;
                    }
                    e.IsSelected = false;
                }
            });
            DeselectAllEvents = new DelegateCommand(() =>
            {
                foreach (var e in Events)
                {
                    e.IsSelected = false;
                }
            });
            OnDropItems = new DelegateCommand <int?>(destIndex =>
            {
                using (script.BulkEdit("Reorder events"))
                {
                    var selected = new List <SmartEvent>();
                    int d        = destIndex.Value;
                    for (int i = Events.Count - 1; i >= 0; --i)
                    {
                        if (Events[i].IsSelected)
                        {
                            if (i <= destIndex)
                            {
                                d--;
                            }
                            selected.Add(Events[i]);
                            script.Events.RemoveAt(i);
                        }
                    }
                    if (d == -1)
                    {
                        d = 0;
                    }
                    selected.Reverse();
                    foreach (var s in selected)
                    {
                        script.Events.Insert(d++, s);
                    }
                }
            });
            OnDropActions = new DelegateCommand <DropActionsArgs>(data =>
            {
                using (script.BulkEdit("Reorder actions"))
                {
                    var selected = new List <SmartAction>();
                    var d        = data.ActionIndex;
                    for (var eventIndex = 0; eventIndex < Events.Count; eventIndex++)
                    {
                        var e = Events[eventIndex];
                        for (int i = e.Actions.Count - 1; i >= 0; --i)
                        {
                            if (e.Actions[i].IsSelected)
                            {
                                if (eventIndex == data.EventIndex && i < data.ActionIndex)
                                {
                                    d--;
                                }
                                selected.Add(e.Actions[i]);
                                e.Actions.RemoveAt(i);
                            }
                        }
                    }
                    selected.Reverse();
                    foreach (var s in selected)
                    {
                        Events[data.EventIndex].Actions.Insert(d++, s);
                    }
                }
            });
            EditAction = new DelegateCommand <SmartAction>(action => EditActionCommand(action));
            AddEvent   = new DelegateCommand(AddEventCommand);
            AddAction  = new DelegateCommand <NewActionViewModel>(AddActionCommand);

            SaveCommand = new AsyncAutoCommand(SaveAllToDb, null, e =>
            {
                statusbar.PublishNotification(new PlainNotification(NotificationType.Error, "Error while saving script to the database: " + e.Message));
            });

            DeleteAction   = new DelegateCommand <SmartAction>(DeleteActionCommand);
            DeleteSelected = new DelegateCommand(() =>
            {
                if (anyEventSelected)
                {
                    using (script.BulkEdit("Delete events"))
                    {
                        int?nextSelect = firstSelectedIndex;
                        if (multipleEventsSelected)
                        {
                            nextSelect = null;
                        }

                        for (int i = Events.Count - 1; i >= 0; --i)
                        {
                            if (Events[i].IsSelected)
                            {
                                Events.RemoveAt(i);
                            }
                        }

                        if (nextSelect.HasValue)
                        {
                            if (nextSelect.Value < Events.Count)
                            {
                                Events[nextSelect.Value].IsSelected = true;
                            }
                            else if (nextSelect.Value - 1 >= 0 && nextSelect.Value - 1 < Events.Count)
                            {
                                Events[nextSelect.Value - 1].IsSelected = true;
                            }
                        }
                    }
                }
                else if (anyActionSelected)
                {
                    using (script.BulkEdit("Delete actions"))
                    {
                        (int eventIndex, int actionIndex)? nextSelect = firstSelectedActionIndex;
                        if (multipleActionsSelected)
                        {
                            nextSelect = null;
                        }

                        for (int i = 0; i < Events.Count; ++i)
                        {
                            var e = Events[i];
                            for (int j = e.Actions.Count - 1; j >= 0; --j)
                            {
                                if (e.Actions[j].IsSelected)
                                {
                                    e.Actions.RemoveAt(j);
                                }
                            }
                        }

                        if (nextSelect.HasValue && nextSelect.Value.actionIndex < Events[nextSelect.Value.eventIndex].Actions.Count)
                        {
                            Events[nextSelect.Value.eventIndex].Actions[nextSelect.Value.actionIndex].IsSelected = true;
                        }
                    }
                }
            });

            UndoCommand = new DelegateCommand(history.Undo, () => history.CanUndo);
            RedoCommand = new DelegateCommand(history.Redo, () => history.CanRedo);

            EditSelected = new DelegateCommand(() =>
            {
                if (anyEventSelected)
                {
                    if (!multipleEventsSelected)
                    {
                        EditEventCommand();
                    }
                }
                else if (anyActionSelected && !multipleActionsSelected)
                {
                    EditActionCommand(Events[firstSelectedActionIndex.eventIndex]
                                      .Actions[firstSelectedActionIndex.actionIndex]);
                }
            });

            CopyCommand = new DelegateCommand(() =>
            {
                var selectedEvents = Events.Where(e => e.IsSelected).ToList();
                if (selectedEvents.Count > 0)
                {
                    var lines = string.Join("\n",
                                            selectedEvents.SelectMany((e, index) => e.ToSmartScriptLines(script.EntryOrGuid, script.SourceType, index)).Select(s => s.ToSqlString()));
                    Clipboard.SetText(lines);
                }
                else
                {
                    var selectedActions = Events.SelectMany(e => e.Actions).Where(e => e.IsSelected).ToList();
                    if (selectedActions.Count > 0)
                    {
                        var fakeEvent = new SmartEvent(-1)
                        {
                            ReadableHint = ""
                        };
                        foreach (var a in selectedActions)
                        {
                            fakeEvent.AddAction(a.Copy());
                        }
                        var lines = string.Join("\n", fakeEvent.ToSmartScriptLines(script.EntryOrGuid, script.SourceType, 0).Select(s => s.ToSqlString()));
                        Clipboard.SetText(lines);
                    }
                }
            });
            CutCommand = new DelegateCommand(() =>
            {
                CopyCommand.Execute();
                DeleteSelected.Execute();
            });
            PasteCommand = new DelegateCommand(() =>
            {
                var lines = (Clipboard.GetText() ?? "").Split('\n').Select(line =>
                {
                    if (line.TryToISmartScriptLine(out var s))
                    {
                        return(s);
                    }
                    return(null);
                }).Where(l => l != null).ToList();
                if (lines.Count > 0)
                {
                    if (lines[0].EventType == -1) // actions
                    {
                        int?eventIndex  = null;
                        int?actionIndex = null;
                        using (script.BulkEdit("Paste actions"))
                        {
                            for (int i = 0; i < Events.Count - 1; ++i)
                            {
                                if (Events[i].IsSelected)
                                {
                                    eventIndex = i;
                                }

                                for (int j = Events[i].Actions.Count - 1; j >= 0; j--)
                                {
                                    if (Events[i].Actions[j].IsSelected)
                                    {
                                        eventIndex = i;
                                        if (!actionIndex.HasValue)
                                        {
                                            actionIndex = j;
                                        }
                                        else
                                        {
                                            actionIndex--;
                                        }
                                        //Events[i].Actions.RemoveAt(j);
                                    }
                                }
                            }

                            if (!eventIndex.HasValue)
                            {
                                eventIndex = Events.Count - 1;
                            }

                            if (eventIndex < 0)
                            {
                                return;
                            }

                            if (!actionIndex.HasValue)
                            {
                                actionIndex = Events[eventIndex.Value].Actions.Count - 1;
                            }

                            if (actionIndex < 0)
                            {
                                actionIndex = 0;
                            }

                            DeselectAll.Execute();
                            foreach (var smartAction in lines.Select(line => script.SafeActionFactory(line)))
                            {
                                Events[eventIndex.Value].Actions.Insert(actionIndex.Value, smartAction);
                                smartAction.IsSelected = true;
                                actionIndex++;
                            }
                        }
                    }
                    else
                    {
                        int?index = null;
                        using (script.BulkEdit("Paste events"))
                        {
                            for (int i = Events.Count - 1; i >= 0; --i)
                            {
                                if (Events[i].IsSelected)
                                {
                                    if (!index.HasValue)
                                    {
                                        index = i;
                                    }
                                    else
                                    {
                                        index--;
                                    }
                                    //Events.RemoveAt(i);
                                }
                            }
                            if (!index.HasValue)
                            {
                                index = Events.Count;
                            }
                            script.InsertFromClipboard(index.Value, lines);
                        }
                    }
                }
            });

            Action <bool, int> selectionUpDown = (addToSelection, diff) =>
            {
                if (anyEventSelected)
                {
                    var selectedEventIndex = Math.Clamp(firstSelectedIndex + diff, 0, Events.Count - 1);
                    if (!addToSelection)
                    {
                        DeselectAll.Execute();
                    }
                    Events[selectedEventIndex].IsSelected = true;
                }
                else if (anyActionSelected)
                {
                    var nextActionIndex = firstSelectedActionIndex.actionIndex + diff;
                    var nextEventIndex  = firstSelectedActionIndex.eventIndex;
                    while (nextActionIndex == -1 || nextActionIndex >= Events[nextEventIndex].Actions.Count)
                    {
                        nextEventIndex += diff;
                        if (nextEventIndex >= 0 && nextEventIndex < Events.Count)
                        {
                            nextActionIndex = diff > 0 ? (Events[nextEventIndex].Actions.Count > 0 ? 0 : -1) : Events[nextEventIndex].Actions.Count - 1;
                        }
                        else
                        {
                            break;
                        }
                    }

                    if (nextActionIndex != -1 && nextEventIndex >= 0 && nextEventIndex < Events.Count)
                    {
                        DeselectAll.Execute();
                        Events[nextEventIndex].Actions[nextActionIndex].IsSelected = true;
                    }
                }
                else
                {
                    if (Events.Count > 0)
                    {
                        Events[diff > 0 ? 0 : Events.Count - 1].IsSelected = true;
                    }
                }
            };

            SelectionUp   = new DelegateCommand <bool?>(addToSelection => selectionUpDown(addToSelection ?? false, -1));
            SelectionDown = new DelegateCommand <bool?>(addToSelection => selectionUpDown(addToSelection ?? false, 1));
            SelectionLeft = new DelegateCommand(() =>
            {
                if (!anyEventSelected && anyActionSelected)
                {
                    var actionEventIndex = firstSelectedActionIndex;
                    DeselectAll.Execute();
                    Events[actionEventIndex.eventIndex].IsSelected = true;
                }
                else if (!anyEventSelected && !anyActionSelected)
                {
                    selectionUpDown(false, -1);
                }
            });
            SelectionRight = new DelegateCommand(() =>
            {
                if (!anyEventSelected)
                {
                    selectionUpDown(false, -1);
                }
                if (anyEventSelected)
                {
                    var eventIndex = firstSelectedIndex;
                    if (Events[eventIndex].Actions.Count > 0)
                    {
                        DeselectAll.Execute();
                        Events[eventIndex].Actions[0].IsSelected = true;
                    }
                }
            });

            SelectAll = new DelegateCommand(() =>
            {
                foreach (var e in Events)
                {
                    e.IsSelected = true;
                }
            });

            this.history.PropertyChanged += (sender, args) =>
            {
                UndoCommand.RaiseCanExecuteChanged();
                RedoCommand.RaiseCanExecuteChanged();
            };

            token = eventAggregator.GetEvent <EventRequestGenerateSql>().Subscribe((args) =>
            {
                if (args.Item is SmartScriptSolutionItem)
                {
                    var itemm = args.Item as SmartScriptSolutionItem;
                    if (itemm.Entry == _item.Entry && itemm.SmartType == _item.SmartType)
                    {
                        args.Sql = new SmartScriptExporter(script, smartFactory).GetSql();
                    }
                }
            });
        }
コード例 #15
0
        public PacketDocumentViewModel(PacketDocumentSolutionItem solutionItem,
                                       IMainThread mainThread,
                                       MostRecentlySearchedService mostRecentlySearchedService,
                                       IDatabaseProvider databaseProvider,
                                       Func <INativeTextDocument> nativeTextDocumentCreator,
                                       IMessageBoxService messageBoxService,
                                       IPacketFilteringService filteringService,
                                       IDocumentManager documentManager,
                                       ITextDocumentService textDocumentService,
                                       IWindowManager windowManager,
                                       IPacketViewerSettings packetSettings,
                                       IEnumerable <IPacketDumperProvider> dumperProviders,
                                       ISniffLoader sniffLoader)
        {
            this.solutionItem      = solutionItem;
            this.mainThread        = mainThread;
            this.messageBoxService = messageBoxService;
            this.filteringService  = filteringService;
            this.sniffLoader       = sniffLoader;
            packetViewModelCreator = new PacketViewModelFactory(databaseProvider);
            MostRecentlySearched   = mostRecentlySearchedService.MostRecentlySearched;
            Title                 = "Sniff " + Path.GetFileNameWithoutExtension(solutionItem.File);
            SolutionItem          = solutionItem;
            FilterText            = nativeTextDocumentCreator();
            SelectedPacketPreview = nativeTextDocumentCreator();
            Watch(this, t => t.FilteringProgress, nameof(ProgressUnknown));

            filteredPackets    = AllPackets;
            ApplyFilterCommand = new AsyncCommand(async() =>
            {
                if (inApplyFilterCommand)
                {
                    return;
                }

                inApplyFilterCommand     = true;
                MostRecentlySearchedItem = FilterText.ToString();
                inApplyFilterCommand     = false;

                if (!string.IsNullOrEmpty(FilterText.ToString()))
                {
                    mostRecentlySearchedService.Add(FilterText.ToString());
                }

                if (currentActionToken != filteringToken)
                {
                    throw new Exception("Invalid concurrent access!");
                }
                filteringToken?.Cancel();
                filteringToken     = null;
                currentActionToken = null;
                await FilterPackets(FilterText.ToString());
            });

            SaveToFileCommand = new AsyncCommand(async() =>
            {
                var path = await windowManager.ShowSaveFileDialog("Text file|txt");
                if (path == null)
                {
                    return;
                }

                LoadingInProgress   = true;
                FilteringInProgress = true;
                try
                {
                    await using StreamWriter writer = File.CreateText(path);
                    int i     = 0;
                    int count = FilteredPackets.Count;
                    foreach (var packet in FilteredPackets)
                    {
                        await writer.WriteLineAsync(packet.Text);
                        if ((i % 100) == 0)
                        {
                            Report(i * 1.0f / count);
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    await this.messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                            .SetTitle("Fatal error")
                                                            .SetMainInstruction("Fatal error during saving file")
                                                            .SetContent(e.Message)
                                                            .WithOkButton(false)
                                                            .Build());
                }
                LoadingInProgress   = false;
                FilteringInProgress = false;
            });

            OpenHelpCommand = new DelegateCommand(() => windowManager.OpenUrl("https://github.com/BAndysc/WoWDatabaseEditor/wiki/Packet-Viewer"));

            On(() => SelectedPacket, doc =>
            {
                if (doc != null)
                {
                    SelectedPacketPreview.FromString(doc.Text);
                }
            });

            On(() => SplitUpdate, _ =>
            {
                SplitPacketsIfNeededAsync().Wait();
                ((ICommand)ApplyFilterCommand).Execute(null);
            });

            foreach (var dumper in dumperProviders)
            {
                Processors.Add(new(dumper));
            }

            RunProcessors = new AsyncAutoCommand(async() =>
            {
                var processors = Processors.Where(s => s.IsChecked).ToList();
                if (processors.Count == 0)
                {
                    return;
                }

                LoadingInProgress   = true;
                FilteringInProgress = true;
                try
                {
                    var tokenSource = new CancellationTokenSource();
                    AssertNoOnGoingTask();
                    currentActionToken = tokenSource;

                    var output = await RunProcessorsThreaded(processors, tokenSource.Token).ConfigureAwait(true);

                    if (!tokenSource.IsCancellationRequested)
                    {
                        var extension = processors.Select(p => p.Extension).Distinct().Count() == 1
                            ? processors[0].Extension
                            : "txt";
                        documentManager.OpenDocument(textDocumentService.CreateDocument($"{processors[0].Name} ({Title})", output, extension));
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                    await messageBoxService.ShowDialog(new MessageBoxFactory <bool>()
                                                       .SetIcon(MessageBoxIcon.Error)
                                                       .SetTitle("Fatal error")
                                                       .SetMainInstruction("Fatal error during processing")
                                                       .SetContent(
                                                           "Sorry, fatal error occured, this is probably a bug in processors, please report it in github\n\n" + e)
                                                       .WithOkButton(true)
                                                       .Build());
                }
                LoadingInProgress   = false;
                FilteringInProgress = false;
                currentActionToken  = null;
            }, _ => Processors.Any(c => c.IsChecked));

            foreach (var proc in Processors)
            {
                AutoDispose(proc.ToObservable(p => p.IsChecked)
                            .SubscribeAction(_ => RunProcessors.RaiseCanExecuteChanged()));
            }

            wrapLines   = packetSettings.Settings.WrapLines;
            splitUpdate = packetSettings.Settings.AlwaysSplitUpdates;
            if (!string.IsNullOrEmpty(packetSettings.Settings.DefaultFilter))
            {
                FilterText.FromString(packetSettings.Settings.DefaultFilter);
            }
            LoadSniff().ListenErrors();

            AutoDispose(new ActionDisposable(() => currentActionToken?.Cancel()));
        }