/// <summary>
        /// Pushes a <see cref="Command"/> into the undo stack or appends it to the currently active transaction,
        /// if one such exists
        /// </summary>
        /// <param name="command">The command</param>
        /// <exception cref="exception.IrreversibleCommandDuringActiveUndoRedoTransactionException">
        /// When trying to push a irreversible <see cref="Command"/> during an active transaction
        /// </exception>
        private void pushCommand(Command command)
        {
            if (IsTransactionActive)
            {
                if (!command.CanUnExecute)
                {
                    throw new exception.IrreversibleCommandDuringActiveUndoRedoTransactionException(
                              "Can not execute an irreversible command when a transaction is active");
                }
                CompositeCommand             compo = mActiveTransactions.Peek();
                ObjectListProvider <Command> list  = compo.ChildCommands;
                list.Insert(list.Count, command);
                command.ParentComposite = compo;
            }
            else
            {
                if (command.CanUnExecute)
                {
                    mUndoStack.Push(command);

                    if (mRedoStack.Contains(m_DirtyMarkerCommand))
                    {
                        m_DirtyMarkerCommand = null;
                    }
                    mRedoStack.Clear();
                }
                else
                {
                    FlushCommands();
                }
            }
        }
Exemplo n.º 2
0
        /// <summary>
        /// Append commands to transfer the attributes of a node to another (used, TODO, role, page number)
        /// </summary>
        public static void AppendCopyNodeAttributes(CompositeCommand command, ProjectView.ProjectView view,
                                                    EmptyNode from, EmptyNode to)
        {
            if (from.TODO && !to.TODO)
            {
                command.ChildCommands.Insert(command.ChildCommands.Count, new Commands.Node.ToggleNodeTODO(view, to));
            }
            if ((!from.Used && to.Used) && (to.Role_ != EmptyNode.Role.Page && to.Role_ != EmptyNode.Role.Heading))
            {
                command.ChildCommands.Insert(command.ChildCommands.Count, new Commands.Node.ToggleNodeUsed(view, to));
            }

            // role of next phrase is copied to selected phrase only when next phrase is page, heading or silence.
            // The priority is highest for page, followed by heading followed by silence. If next phrase is of higher priority only then its role is copied.
            if (from.Role_ == EmptyNode.Role.Page && to.Role_ != EmptyNode.Role.Page)
            {
                command.ChildCommands.Insert(command.ChildCommands.Count, new Commands.Node.SetPageNumber(view, to, from.PageNumber.Clone()));
            }
            else if ((to.Role_ != EmptyNode.Role.Heading && to.Role_ != EmptyNode.Role.Page) &&
                     (from.Role_ != EmptyNode.Role.Plain &&
                      (from.Role_ != EmptyNode.Role.Silence || to is PhraseNode)))
            {
                if (from.Role_ == EmptyNode.Role.Heading && to.Role_ != EmptyNode.Role.Page)
                {
                    command.ChildCommands.Insert(command.ChildCommands.Count, new Commands.Node.AssignRole(view, from, EmptyNode.Role.Plain, null));
                    command.ChildCommands.Insert(command.ChildCommands.Count, new Commands.Node.AssignRole(view, to, EmptyNode.Role.Heading, null));
                }
                else
                {
                    command.ChildCommands.Insert(command.ChildCommands.Count, new Commands.Node.AssignRole(view, to, from.Role_, from.CustomRole));
                }
            }
        }
        protected override void OnDeleteCommandExecutedOverride(object sender, ExecutedRoutedEventArgs e)
        {
            var compositeRemoveCommand = new CompositeCommand("Remove Connections");
            foreach (var item in this.SelectedItems)
            {
                var container = this.ContainerGenerator.ContainerFromItem(item) as IShape;
                if (container != null)
                {
                    foreach (var connection in this.GetConnectionsForShape(container).ToList())
                    {
                        compositeRemoveCommand.AddCommand(new UndoableDelegateCommand("Remove Connection",
                                                                 new Action<object>((o) => this.RemoveConnection(connection)),
                                                                 new Action<object>((o) => this.AddConnection(connection))));
                    }
                }
            }

            base.OnDeleteCommandExecutedOverride(sender, e);

            if (compositeRemoveCommand.Commands.Count() > 0)
            {
                compositeRemoveCommand.Execute();
                ((this.UndoRedoService.UndoStack.FirstOrDefault() as CompositeCommand).Commands as IList<Telerik.Windows.Diagrams.Core.ICommand>).Add(compositeRemoveCommand);
            }
        }
Exemplo n.º 4
0
        public void ExecuteForCommand()
        {
            ICommand        setX     = new SetVariableCommand("x", new ConstantExpression(0));
            ICommand        setY     = new SetVariableCommand("y", new ConstantExpression(0));
            List <ICommand> commands = new List <ICommand>();

            commands.Add(setX);
            commands.Add(setY);
            ICommand initialCommand = new CompositeCommand(commands);

            IExpression condition = new CompareExpression(ComparisonOperator.Less, new VariableExpression("x"), new ConstantExpression(6));

            IExpression addXtoY = new ArithmeticBinaryExpression(ArithmeticOperator.Add, new VariableExpression("y"), new VariableExpression("x"));
            ICommand    addToY  = new SetVariableCommand("y", addXtoY);

            ICommand endCommand = new SetVariableCommand("x", new ArithmeticBinaryExpression(ArithmeticOperator.Add, new VariableExpression("x"), new ConstantExpression(1)));

            ForCommand forcmd = new ForCommand(initialCommand, condition, endCommand, addToY);

            BindingEnvironment environment = new BindingEnvironment();

            environment.SetValue("y", null);

            forcmd.Execute(environment);

            Assert.AreEqual(15, environment.GetValue("y"));
        }
Exemplo n.º 5
0
        public void ExecuteCompositeCommand()
        {
            BindingEnvironment environment = new BindingEnvironment();

            SetVariableCommand command1 = new SetVariableCommand("foo", new ConstantExpression("bar"));
            SetVariableCommand command2 = new SetVariableCommand("one", new ConstantExpression(1));
            SetVariableCommand command3 = new SetVariableCommand("bar", new VariableExpression("foo"));

            List <ICommand> commands = new List <ICommand>();

            commands.Add(command1);
            commands.Add(command2);
            commands.Add(command3);

            CompositeCommand command = new CompositeCommand(commands);

            environment.SetValue("foo", null);
            environment.SetValue("one", null);

            command.Execute(environment);

            Assert.AreEqual("bar", environment.GetValue("foo"));
            Assert.AreEqual(1, environment.GetValue("one"));
            Assert.AreEqual("bar", environment.GetValue("bar"));
        }
Exemplo n.º 6
0
        public void ExecuteWhileCommand()
        {
            IExpression     incrementX = new ArithmeticBinaryExpression(ArithmeticOperator.Add, new ConstantExpression(1), new VariableExpression("x"));
            IExpression     decrementY = new ArithmeticBinaryExpression(ArithmeticOperator.Subtract, new VariableExpression("y"), new ConstantExpression(1));
            ICommand        setX       = new SetVariableCommand("x", incrementX);
            ICommand        setY       = new SetVariableCommand("y", decrementY);
            List <ICommand> commands   = new List <ICommand>();

            commands.Add(setX);
            commands.Add(setY);
            ICommand    command = new CompositeCommand(commands);
            IExpression yexpr   = new VariableExpression("y");

            WhileCommand whilecmd = new WhileCommand(yexpr, command);

            BindingEnvironment environment = new BindingEnvironment();

            environment.SetValue("x", 0);
            environment.SetValue("y", 5);

            whilecmd.Execute(environment);

            Assert.AreEqual(0, environment.GetValue("y"));
            Assert.AreEqual(5, environment.GetValue("x"));
        }
Exemplo n.º 7
0
        public MainPageViewModel(INavigationService navService, IDialogService dialogService, ISettingService settingService, IResourceLoader resourceLoader)
        {
            _navService      = navService;
            _dialogService   = dialogService;
            _settingService  = settingService;
            _resourceLoader  = resourceLoader;
            CurrentPageIndex = 1;
            MaxPageIndex     = 2;
            TrangDocTruyen   = Wrapper.SiteTruyen.LuongSonBac;
            TheLoaiDangXem   = Wrapper.TagTruyen.Default;
            GenerateData();
            IsLoading              = false;
            JumpPageCommand        = new DelegateCommand <string>(AddPage);
            LoadingNextPageCommand = new CompositeCommand();
            LoadingNextPageCommand.RegisterCommand(JumpPageCommand);
            LoadingNextPageCommand.RegisterCommand(LoadingTheLoaiCommand);
            LoadingPreviousCommand = new CompositeCommand();
            LoadingPreviousCommand.RegisterCommand(JumpPageCommand);
            LoadingPreviousCommand.RegisterCommand(LoadingTheLoaiCommand);


            NavigateChapterCommand  = new DelegateCommand <object>(NavigateChapter);
            FirstLoadCommand        = new DelegateCommand(FisrtLoad);
            SearchPageCommand       = new DelegateCommand <string>(Search);
            ClearSearchPageCommand  = new DelegateCommand(ClearSearch);
            ChangeSiteTruyenCommand = new DelegateCommand <SiteTruyenVM>(
                async(value) =>
            {
                ChangeSiteTruyen(value);
                await LoadingTheLoaiCommand.Execute();
            });
            ListViewScrollValue = 0;
        }
Exemplo n.º 8
0
 public static CompositeCommand GetMergeCommand(ProjectView.ProjectView view, EmptyNode node, EmptyNode next)
 {
     if (node != null && next != null)
     {
         CompositeCommand command =
             view.Presentation.CreateCompositeCommand(Localizer.Message("merge_phrase_with_next"));
         if (node is PhraseNode)
         {
             AppendCopyNodeAttributes(command, view, next, node);
             if (next is PhraseNode)
             {
                 command.ChildCommands.Insert(command.ChildCommands.Count, new Commands.Node.MergeAudio(view, (PhraseNode)node, (PhraseNode)next));
             }
             else
             {
                 command.ChildCommands.Insert(command.ChildCommands.Count, new Commands.Node.Delete(view, next));
             }
         }
         else
         {
             AppendCopyNodeAttributes(command, view, node, next);
             command.ChildCommands.Insert(command.ChildCommands.Count, new Commands.Node.Delete(view, node));
         }
         return(command);
     }
     return(null);
 }
Exemplo n.º 9
0
        public static ICommand Then(this ICommand left, ICommand right)
        {
            var command = new CompositeCommand();

            command.Add(left);
            command.Add(right);
            return(command);
        }
 public ArticleViewModel(INewsFeedService newsFeedService,
                         IRegionManager regionManager,
                         IEventAggregator eventAggregator)
 {
     this.saveAllCommand = new CompositeCommand();
     this.saveAllCommand.RegisterCommand(new SaveProductsCommand());
     this.saveAllCommand.RegisterCommand(new SaveOrdersCommand());
 }
Exemplo n.º 11
0
        public static IDisposable RegisterWorkitemCommand(string commandName, IWorkItem workItem, Action action)
        {
            CompositeCommand compositeCommand = GetCompositeCommandByName(commandName, workItem);
            ICommand         command          = new DelegateCommand(action);

            compositeCommand.RegisterCommand(command);
            return(new DisposableAction(() => compositeCommand.UnregisterCommand(command)));
        }
Exemplo n.º 12
0
        public void RunDefaultImageEnchancement()
        {
            var composite = new CompositeCommand();

            composite.Add(new ResizeCommand());
            composite.Add(new BlackAndWhiteFilterCommand());
            composite.Execute();
        }
Exemplo n.º 13
0
        public static CompositeCommand GetSplitCommand(ProjectView.ProjectView view, PhraseNode phrase, double time)
        {
            CompositeCommand command =
                view.Presentation.CreateCompositeCommand(Localizer.Message("split_phrase"));

            AppendSplitCommandWithProperties(view, command, phrase, time, false);
            return(command);
        }
Exemplo n.º 14
0
 public void VisitComposite(CompositeCommand Composite)
 {
     System.Console.WriteLine("Composite");
     foreach (IScriptCommand command in Composite.Commands)
     {
         command.Accept(this);
     }
 }
Exemplo n.º 15
0
        protected ICommand CombineCommands(ICommand command1, ICommand command2)
        {
            CompositeCommand command = new CompositeCommand();

            command.RegisterCommand(command1);
            command.RegisterCommand(command2);
            return(command);
        }
Exemplo n.º 16
0
        private CompositeCommand GetCommandForImportAudioFileInEachSection(PhraseNode phraseNode, SectionNode section)
        {
            CompositeCommand command = m_Presentation.CreateCompositeCommand(Localizer.Message("import_phrases"));

            Commands.Node.AddNode addCmd = new Commands.Node.AddNode(m_ProjectView, phraseNode, section, section.PhraseChildCount, false);
            command.ChildCommands.Insert(command.ChildCommands.Count, addCmd);
            return(command);
        }
 public DeleteExistingEntityCommandExecutor(CompositeCommand command, IRegionManager regionManager, IEventAggregator eventAggregator, IEntityDeleteService <U> entityDeleteService)
 {
     _regionManager       = regionManager;
     _eventAggregator     = eventAggregator;
     _entityDeleteService = entityDeleteService;
     commandHandler       = new DelegateCommand <U>(ExecuteCommand);
     command.RegisterCommand(commandHandler);
 }
Exemplo n.º 18
0
 private void RegisterSingleCommand(CompositeCommand compositeCommand, DelegateCommand command)
 {
     if (compositeCommand.RegisteredCommands.Count > 0)
     {
         compositeCommand.UnregisterCommand(compositeCommand.RegisteredCommands[0]);
     }
     compositeCommand.RegisterCommand(command);
 }
Exemplo n.º 19
0
            public void CanExecuteEmptyCommandWithAtLeastOneMustBeExecutable(bool atLeastOneMustBeExecutable, bool expectedValue)
            {
                var compositeCommand = new CompositeCommand();

                compositeCommand.AtLeastOneMustBeExecutable = atLeastOneMustBeExecutable;

                Assert.AreEqual(expectedValue, ((ICatelCommand)compositeCommand).CanExecute(null));
            }
Exemplo n.º 20
0
 public void RegisteringCommandInItselfThrows()
 {
     Assert.Throws <ArgumentException>(() =>
     {
         var compositeCommand = new CompositeCommand();
         compositeCommand.RegisterCommand(compositeCommand);
     });
 }
Exemplo n.º 21
0
 public void RegisteringCommandWithNullThrows()
 {
     Assert.Throws <ArgumentNullException>(() =>
     {
         var compositeCommand = new CompositeCommand();
         compositeCommand.RegisterCommand(null);
     });
 }
Exemplo n.º 22
0
        /// <summary>
        /// Called when [apply template].
        /// </summary>
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _btnSave          = GetTemplateChild("Part_SaveButton") as Button;
            _btnNext          = GetTemplateChild("Part_NextButton") as Button;
            _btnCancel        = GetTemplateChild("Part_CancelButton") as Button;
            _focusElement     = GetTemplateChild("Part_Focus") as Grid;
            _contentPresenter = GetTemplateChild("PART_ContentPresenter") as ContentPresenter;
            _maximizeGrid     = GetTemplateChild("PART_MaximizeGrid") as Grid;
            _rootGrid         = GetTemplateChild("PART_RootGrid") as Grid;

            _saveCompositeCommand = new CompositeCommand();
            _saveCompositeCommand.RegisterCommand(new DelegateCommand(ExecuteSaveCommand));
            if (SaveCommand != null)
            {
                _saveCompositeCommand.RegisterCommand(SaveCommand);
                if (!_afterSaveCommandIntialized)
                {
                    _afterSaveCommandIntialized = true;
                    _saveCompositeCommand.RegisterCommand(new DelegateCommand(AfterSaveCommandExecute));
                }
            }
            _btnSave.Command = _saveCompositeCommand;
            var contentBinding = new Binding();

            contentBinding.Source = this;
            contentBinding.Path   = new PropertyPath(PropertyUtil.ExtractPropertyName(() => Content));
            _btnSave.SetBinding(ButtonBase.CommandParameterProperty, contentBinding);
            _btnNext.Click   += NextClicked;
            _btnCancel.Click += CancelClick;
            LostFocus        += Content_LostFocus;
            _focusElement.MouseLeftButtonDown += Content_MouseLeftButtonDown;
            AddHandler(MouseLeftButtonDownEvent, new MouseButtonEventHandler(EditableExpander_MouseLeftButtonDown), true);
            MouseLeftButtonDown += EditableExpander_MouseLeftButtonDown;

            if (IsExpanded)
            {
                VisualStateManager.GoToState(this, "RevealState", true);
            }

            if (UsingEditableContentTemplate())
            {
                ContentTemplate = EditableContentTemplate;
            }

            _templateApplied = true;

            UpdateContentPresenter();

            if (IsEditing)
            {
                TurnOnEditing();
            }
            else
            {
                TurnOffEditing();
            }
        }
Exemplo n.º 23
0
        private void PushUndoStack()
        {
            // Undo/Redo
            ISupportUndo    pageVMUndo  = designerCanvas.DataContext as ISupportUndo;
            IGroupOperation pageVMGroup = designerCanvas.DataContext as IGroupOperation;

            if (pageVMUndo == null)
            {
                return;
            }

            CompositeCommand cmds = new CompositeCommand();

            IPagePropertyData Page = designerCanvas.DataContext as IPagePropertyData;
            bool bHasGroup         = Page.GetSelectedwidgets().Any(a => a.IsGroup);

            // Create undoable command for widgets
            foreach (WidgetViewModBase item in _infoItems)
            {
                item.PropertyMementos.SetPropertyNewValue("Left", item.Raw_Left);
                item.PropertyMementos.SetPropertyNewValue("Top", item.Raw_Top);

                if (item.WidgetType == WidgetType.Toast && item.Top != 0)
                {
                    item.PropertyMementos.SetPropertyNewValue("DisplayPosition", ToastDisplayPosition.UserSetting);
                }

                PropertyChangeCommand cmd = new PropertyChangeCommand(item, item.PropertyMementos);
                cmds.AddCommand(cmd);
            }

            // Create undoable command for groups
            if (pageVMGroup != null)
            {
                List <Guid> groupGuids = _groups.Select(x => x.WidgetID).ToList();

                if (designerItem.ParentID != Guid.Empty)
                {
                    groupGuids.Add(designerItem.ParentID);
                }

                if (groupGuids.Count > 0)
                {
                    UpdateGroupCommand cmd = new UpdateGroupCommand(pageVMGroup, groupGuids);
                    cmds.AddCommand(cmd);
                }
            }

            // Push to undo stack
            if (cmds.Count > 0)
            {
                List <IWidgetPropertyData> allSelects = _selectionService.GetSelectedWidgets();
                cmds.AddCommand(new SelectCommand(pageVMGroup, allSelects));

                cmds.DeselectAllWidgetsFirst();
                pageVMUndo.UndoManager.Push(cmds);
            }
        }
Exemplo n.º 24
0
        public void RegisteringCommandTwiceThrows()
        {
            var compositeCommand = new CompositeCommand();
            var duplicateCommand = new TestCommand();

            compositeCommand.RegisterCommand(duplicateCommand);

            compositeCommand.RegisterCommand(duplicateCommand);
        }
        /// <summary>
        /// Fires the <see cref="TransactionCancelled"/> event
        /// </summary>
        private void NotifyTransactionCancelled(CompositeCommand command)
        {
            EventHandler <TransactionCancelledEventArgs> d = TransactionCancelled;

            if (d != null)
            {
                d(this, new TransactionCancelledEventArgs(this, command));
            }
        }
Exemplo n.º 26
0
 /// <summary>
 /// Constructor estático.
 /// </summary>
 static EditionCommands()
 {
     activateRecordCommand = new CompositeCommand();
     deleteRecordCommand   = new CompositeCommand();
     editRecordCommand     = new CompositeCommand();
     getRecordsCommand     = new CompositeCommand();
     newRecordCommand      = new CompositeCommand();
     saveRecordCommand     = new CompositeCommand();
 }
Exemplo n.º 27
0
        public static void Behavioral_CommandComposite()
        {
            // This is a composite command
            var composite = new CompositeCommand();

            composite.Add(new ResizeCommand());
            composite.Add(new BlackAndWhiteCommand());
            composite.Execute();
        }
Exemplo n.º 28
0
        static void TestCompositeCommand()
        {
            var composite = new CompositeCommand();

            composite.Add(new ResizeCommand());
            composite.Add(new BlackAndWhiteCommand());

            composite.Execute();
        }
Exemplo n.º 29
0
        public void DecompileCompositeCommand()
        {
            IExpression expression = new ArithmeticBinaryExpression(ArithmeticOperation.Add, new ConstantExpression(1), new ConstantExpression(2));
            ICommand    command1   = new SetCommand("a", expression);
            ICommand    command2   = new SetCommand("b", expression);
            ICommand    command    = new CompositeCommand(new ICommand[] { command1, command2 });

            Assert.AreEqual("{\r\na = (1 + 2);\r\nb = (1 + 2);\r\n}\r\n", this.Decompile(command));
        }
Exemplo n.º 30
0
        private static void EvaluateCommands(string text, Context context)
        {
            Parser parser = new Parser(text);

            var result = parser.ParseCommands();

            var command = new CompositeCommand(result);

            command.Execute(context);
        }
Exemplo n.º 31
0
        private UndoableDelegateCommand CreateRemoveConnectionCommand(IConnection connection)
        {
            var compositeRemoveConnectionCommand = new CompositeCommand(CommandNames.RemoveConnections);

            UndoableDelegateCommand removeCommand = new UndoableDelegateCommand(CommandNames.RemoveConnection, s => this.Diagram.RemoveConnection(connection), s => this.Diagram.AddConnection(connection));

            compositeRemoveConnectionCommand.AddCommand(removeCommand);

            return(compositeRemoveConnectionCommand);
        }
Exemplo n.º 32
0
        public void CanExecuteChangedWithMultipleCommands()
        {
            var command1 = new DelegateCommand(() => { }, () => true);
            var command2 = new DelegateCommand<int>(i => { }, _ => true);

            var compositeCommand = new CompositeCommand();
            bool canExecuteEventFired = false;
            EventHandler eventHandler = (sender, eventArgs) =>
                                        {
                                            Assert.AreSame(compositeCommand, sender);
                                            Assert.IsNotNull(eventArgs);
                                            canExecuteEventFired = true;
                                        };
            compositeCommand.CanExecuteChanged += eventHandler;
            compositeCommand.RegisterCommand(command1);
            compositeCommand.RegisterCommand(command2);

            Assert.IsFalse(EventConsumer.EventCalled);

            command1.RaiseCanExecuteChanged();
            Assert.IsTrue(canExecuteEventFired);

            canExecuteEventFired = false;
            command2.RaiseCanExecuteChanged();
            Assert.IsTrue(canExecuteEventFired);

            canExecuteEventFired = false;
            compositeCommand.UnregisterCommand(command1);
            Assert.IsTrue(canExecuteEventFired);  // Unregister also raises CanExecuteChanged.

            canExecuteEventFired = false;
            command1.RaiseCanExecuteChanged();
            Assert.IsFalse(canExecuteEventFired);
            command2.RaiseCanExecuteChanged();
            Assert.IsTrue(canExecuteEventFired);

            canExecuteEventFired = false;
            compositeCommand.UnregisterCommand(command2);
            Assert.IsTrue(canExecuteEventFired);  // Unregister also raises CanExecuteChanged.

            canExecuteEventFired = false;
            command1.RaiseCanExecuteChanged();
            command2.RaiseCanExecuteChanged();
            Assert.IsFalse(canExecuteEventFired);
        }
		private void DeleteShape(IShape shape)
		{
			var compositeRemoveShapeCommand = new CompositeCommand(CommandNames.RemoveShapes);
			var observableGraphSource = this.GraphSource as IObservableGraphSource;
			if (observableGraphSource != null)
			{
				foreach (var connection in this.GetConnectionsForShape(shape))
				{
					compositeRemoveShapeCommand.AddCommand(this.CreateRemoveConnectionCommand(connection, observableGraphSource));
					if (!shape.Equals(connection.Target))
					{
						compositeRemoveShapeCommand.AddCommand(this.CreateRemoveShapeCommand(connection.Target, observableGraphSource));
					}
				}

				compositeRemoveShapeCommand.AddCommand(this.CreateRemoveShapeCommand(shape, observableGraphSource));

				this.UndoRedoService.ExecuteCommand(compositeRemoveShapeCommand);
			}
		}
Exemplo n.º 34
0
        public void CanExecuteWithMultipleCommands()
        {
            bool canExecuteCommand1 = false;
            bool canExecuteCommand2 = false;
            var command1 = new DelegateCommand(
              () => { },
              () => canExecuteCommand1);
            var command2 = new DelegateCommand<int>(
              i => Assert.AreEqual(123, i),
              i =>
              {
                  Assert.AreEqual(123, i);
                  return canExecuteCommand2;
              });

            var compositeCommand = new CompositeCommand();
            Assert.IsFalse(compositeCommand.CanExecute(123));

            compositeCommand.RegisterCommand(command1);
            compositeCommand.RegisterCommand(command2);
            Assert.IsFalse(compositeCommand.CanExecute(123));

            canExecuteCommand1 = true;
            Assert.IsFalse(compositeCommand.CanExecute(123));

            canExecuteCommand2 = true;
            Assert.IsTrue(compositeCommand.CanExecute(123));

            canExecuteCommand1 = false;
            compositeCommand.UnregisterCommand(command1);
            Assert.IsTrue(compositeCommand.CanExecute(123));

            canExecuteCommand2 = false;
            Assert.IsFalse(compositeCommand.CanExecute(123));

            canExecuteCommand1 = true;
            canExecuteCommand2 = true;
            compositeCommand.UnregisterCommand(command2);
            Assert.IsFalse(compositeCommand.CanExecute(123));
        }
Exemplo n.º 35
0
	// Use this for initialization
	void Start(){
		t = new EnterFrameTimer(200);
		t.OnTimer = onTimer;
		t.Start();

		ConsoleCommand command;
		CompositeCommand cc = new CompositeCommand(CompositeCommandMode.SEQUENCE);
		cc.OnCommandItemComplete = delegate(AbstractCommand _command) {
			Debug.Log("Item Complete" + " " + (_command as ConsoleCommand).index.ToString());
		};
		cc.OnCommandComplete = delegate(AbstractCommand _command) {
			Debug.Log("All Complete");
		};
		int max = 10;
		for (int i = 0; i < max; i++) {
			command = new ConsoleCommand();
			command.index = i;
			cc.AddCommand(command);
		}

		cc.Execute();

	}
		internal void CommitItemFontColor(Brush oldFontColor, Brush newFontColor)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand("Change Items Font Color");

			foreach (var item in this.SelectedItems)
			{
				var ensureDifferentItem = item;
				var command = new UndoableDelegateCommand("Change Item Font Color",
					p =>
						{
							if (newFontColor != null)
							{
								ensureDifferentItem.Foreground = newFontColor;
							}
						},
					p =>
						{
							if (oldFontColor != null)
							{
								ensureDifferentItem.Foreground = oldFontColor;
							}
						});
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);
		}
        public override LineBufferOperationResults InsertLines(
			int lineIndex,
			int count)
        {
            var composite = new CompositeCommand<BlockCommandContext>(true, false);

            using (project.Blocks.AcquireLock(RequestLock.Write))
            {
                for (int i = 0;
                    i < count;
                    i++)
                {
                    var block = new Block(project.Blocks);
                    var command = new InsertIndexedBlockCommand(lineIndex, block);
                    composite.Commands.Add(command);
                }

                var context = new BlockCommandContext(project);
                project.Commands.Do(composite, context);

                return GetOperationResults();
            }
        }
        private CompositeCommand CreateRemoveShapeCommand(RadDiagramShapeBase shape)
        {
            if (shape == null) return null;
            var compositeRemoveShapeCommand = new CompositeCommand(CommandNames.RemoveShapes);
            var removeCommand = new UndoableDelegateCommand(CommandNames.RemoveShape, s => this.Diagram.RemoveShape(shape), s => this.Diagram.AddShape(shape));

            var parentContainer = shape.ParentContainer;
            if (parentContainer != null)
            {
                var execute = new Action<object>((o) => parentContainer.RemoveItem(shape));
                var undo = new Action<object>((o) =>
                {
                    if (!parentContainer.Items.Contains(shape))
                        parentContainer.AddItem(shape);
                });
                compositeRemoveShapeCommand.AddCommand(new UndoableDelegateCommand(CommandNames.RemoveItemFromContainer, execute, undo));
            }

            foreach (var changeSourceCommand in shape.OutgoingLinks.Union(shape.IncomingLinks).ToList().Select(connection => this.CreateRemoveConnectionCommand(connection)))
            {
                compositeRemoveShapeCommand.AddCommand(changeSourceCommand);
            }

            compositeRemoveShapeCommand.AddCommand(removeCommand);

            var container = shape as RadDiagramContainerShape;
            if (container != null)
            {
                for (int i = container.Items.Count - 1; i >= 0; i--)
                {
                    var shapeToRemove = container.Items[i] as RadDiagramShapeBase;
                    if (shapeToRemove != null)
                        compositeRemoveShapeCommand.AddCommand(this.CreateRemoveShapeCommand(shapeToRemove));
                    else
                    {
                        var connection = container.Items[i] as IConnection;
                        if (connection != null && connection.Source == null && connection.Target == null)
                            compositeRemoveShapeCommand.AddCommand(this.CreateRemoveConnectionCommand(container.Items[i] as IConnection));
                    }
                }
            }

            return compositeRemoveShapeCommand;
        }
        private UndoableDelegateCommand CreateRemoveConnectionCommand(IConnection connection)
        {
            var compositeRemoveConnectionCommand = new CompositeCommand(CommandNames.RemoveConnections);

            UndoableDelegateCommand removeCommand = new UndoableDelegateCommand(CommandNames.RemoveConnection, s => this.Diagram.RemoveConnection(connection), s => this.Diagram.AddConnection(connection));

            compositeRemoveConnectionCommand.AddCommand(removeCommand);

            return compositeRemoveConnectionCommand;
        }
        private void OnItemsChanging(object sender, DiagramItemsChangingEventArgs e)
        {
            if (this.isClear) return;

            if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
            {
                var rowModel = e.OldItems.ElementAt(0) as RowModel;
                var command = new CompositeCommand("Remove Connections");
                if (rowModel != null)
                {
                    this.RemoveRowModel(rowModel, command);
                    if (command.Commands.Count() > 0)
                        this.diagram.UndoRedoService.ExecuteCommand(command);
                }
                else
                {
                    var tableModel = e.OldItems.ElementAt(0) as TableModel;
                    if (tableModel != null)
                    {
                        foreach (var item in tableModel.InternalItems)
                        {
                            this.RemoveRowModel(item as RowModel, command);
                        }
                        if (command.Commands.Count() > 0)
                            this.diagram.UndoRedoService.ExecuteCommand(command);

                        tableModel.InternalItems.Clear();
                    }
                }
            }
        }
		internal void CommitConnectionTargetCapType(CapType? oldTargetCapType, CapType? newTargetCapType)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand("Change Connections Target Cap Type");

			foreach (var conn in this.SelectedConnections)
			{
				var ensureDifferentConnection = conn;
				var command = new UndoableDelegateCommand("Change Connection Target Cap Type",
					p => ensureDifferentConnection.TargetCapType = newTargetCapType.HasValue ? newTargetCapType.Value : CapType.None,
					p => ensureDifferentConnection.TargetCapType = oldTargetCapType.HasValue ? oldTargetCapType.Value : CapType.None);
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);
		}
        private void RemoveContainer(MainContainerShapeBase container, RadDiagramShapeBase itemToRemove)
        {
            if (container == null || itemToRemove == null) return;

            CompositeCommand command = new CompositeCommand("Remove horizontal container");
            if (container.IsCollapsed)
            {
                command.AddCommand(new UndoableDelegateCommand("Update container",
                   new Action<object>((o) =>
                   {
                       container.IsCollapsed = false;
                   }),
                   new Action<object>((o) =>
                   {
                       container.IsCollapsed = true;
                   })));
            }
            command.AddCommand(this.CreateRemoveShapeCommand(itemToRemove));
            if (container.IsCollapsed)
            {
                command.AddCommand(new UndoableDelegateCommand("Update container",
                   new Action<object>((o) =>
                   {
                   }),
                   new Action<object>((o) =>
                   {
                   })));
            }

            this.Diagram.UndoRedoService.ExecuteCommand(command);
        }
		internal void CommitShapeHeight(double newHeight)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand(CommandNames.ResizeShapes);

			foreach (var shape in this.SelectedShapes)
			{
				var ensureDifferentShape = shape;
				var ensureOldValue = ensureDifferentShape.Height;
				var command = new UndoableDelegateCommand(CommandNames.ResizeShape,
					p => ensureDifferentShape.Height = newHeight,
					p => ensureDifferentShape.Height = ensureOldValue);
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);

			this.OnBoundsChanged();
		}
Exemplo n.º 44
0
        public void CanExecuteChangedEventShouldBeWeak()
        {
            var command1 = new DelegateCommand(() => { }, null);
            var command2 = new DelegateCommand<int>(i => { }, null);

            var compositeCommand = new CompositeCommand();
            compositeCommand.RegisterCommand(command1);
            compositeCommand.RegisterCommand(command2);
            compositeCommand.CanExecuteChanged += new EventConsumer().EventHandler;

            // Garbage collect the EventConsumer.
            GC.Collect();

            EventConsumer.Clear();
            command1.RaiseCanExecuteChanged();
            command2.RaiseCanExecuteChanged();
            Assert.IsFalse(EventConsumer.EventCalled);
        }
		internal void CommitItemStrokeThickness(double oldStrokeThickness, double newStrokeThickness)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand("Change Items Border Thickness");

			foreach (var item in this.SelectedItems)
			{
				var ensureDifferentItem = item;
				var command = new UndoableDelegateCommand("Change Item Border Thikness",
					p => ensureDifferentItem.StrokeThickness = newStrokeThickness,
					p => ensureDifferentItem.StrokeThickness = oldStrokeThickness);
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);
		}
Exemplo n.º 46
0
        public void ExecuteMultipleCommands()
        {
            bool command1Called = false;
            bool command2Called = false;
            var command1 = new DelegateCommand(
              () => command1Called = true,
              () => true);
            var command2 = new DelegateCommand<int>(
              i =>
              {
                  Assert.AreEqual(123, i);
                  command2Called = true;
              },
              i =>
              {
                  Assert.AreEqual(123, i);
                  return true;
              });

            var compositeCommand = new CompositeCommand();
            compositeCommand.RegisterCommand(command1);
            compositeCommand.RegisterCommand(command2);

            compositeCommand.Execute(123);
            Assert.IsTrue(command1Called);
            Assert.IsTrue(command2Called);

            command1Called = false;
            command2Called = false;
            compositeCommand.UnregisterCommand(command1);

            compositeCommand.Execute(123);
            Assert.IsFalse(command1Called);
            Assert.IsTrue(command2Called);
        }
		internal void CommitItemStrokeDashArray(DoubleCollection oldStrokeDashArray, DoubleCollection newStrokeDashArray)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand("Change Items Border Dash Style");

			foreach (var item in this.SelectedItems)
			{
				var ensureDifferentItem = item;
				var command = new UndoableDelegateCommand("Change Item Border Dash Style",
					p => ensureDifferentItem.StrokeDashArray = newStrokeDashArray,
					p => ensureDifferentItem.StrokeDashArray = oldStrokeDashArray);
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);
		}
        private void RemoveRowModel(RowModel rowModel, CompositeCommand command)
        {
            var container = this.diagram.ContainerGenerator.ContainerFromItem(rowModel) as IShape;
            if (container == null) return;

            foreach (var connection in this.diagram.GetConnectionsForShape(container).ToList())
            {
                var link = this.diagram.ContainerGenerator.ItemFromContainer(connection) as LinkViewModelBase<NodeViewModelBase>;
                command.AddCommand(new UndoableDelegateCommand(
                    "Remove link",
                    new Action<object>((o) => this.dc.RemoveLink(link)),
                    new Action<object>((o) => this.dc.AddLink(link))));
            }
        }
		internal void CommitItemColorStyle(ColorStyle oldColorStyle, ColorStyle newColorStyle)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand("Change Items Color Style");

			foreach (var item in this.SelectedItems)
			{
				var ensureDifferentItem = item;
				var command = new UndoableDelegateCommand("Change Item Color Style",
					p =>
						{
							if (newColorStyle != null)
							{
								ensureDifferentItem.Background = newColorStyle.Fill;
								ensureDifferentItem.BorderBrush = newColorStyle.Stroke;
								ensureDifferentItem.Stroke = newColorStyle.Stroke;
							}
						},
					p =>
						{
							if (oldColorStyle != null)
							{
								ensureDifferentItem.Background = oldColorStyle.Fill;
								ensureDifferentItem.BorderBrush = oldColorStyle.Stroke;
								ensureDifferentItem.Stroke = oldColorStyle.Stroke;
							}
						});
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);
		}
		internal void CommitItemLabel(string oldLabel, string newLabel)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand("Change Items Content");

			foreach (var item in this.SelectedItems)
			{
				var ensureDifferentItem = item;
				var command = new UndoableDelegateCommand("Change Item Content",
					p => ensureDifferentItem.Content = newLabel,
					p => ensureDifferentItem.Content = oldLabel);
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);
		}
		internal void CommitItemFontFamily(FontFamily oldFontFamily, FontFamily newFontFamily)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand("Change Items Font Family");

			foreach (var item in this.SelectedItems)
			{
				var ensureDifferentItem = item;
				var command = new UndoableDelegateCommand("Change Item Font Family",
					p => ensureDifferentItem.FontFamily = newFontFamily,
					p => ensureDifferentItem.FontFamily = oldFontFamily);
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);
		}
        public void ProcessImmediateEdits(
			BlockCommandContext context,
			Block block,
			int textIndex)
        {
            // Get the plugin settings from the project.
            ImmediateBlockTypesSettings settings = Settings;

            // Grab the substring from the beginning to the index and compare that
            // in the dictionary.
            string text = block.Text.Substring(0, textIndex);

            if (!settings.Replacements.ContainsKey(text))
            {
                // We want to fail as fast as possible.
                return;
            }

            // If the block type is already set to the same name, skip it.
            string blockTypeName = settings.Replacements[text];
            BlockType blockType = Project.BlockTypes[blockTypeName];

            if (block.BlockType == blockType)
            {
                return;
            }

            // Perform the substitution with a replace operation and a block change
            // operation.
            var replaceCommand =
                new ReplaceTextCommand(
                    new BlockPosition(block.BlockKey, 0), textIndex, string.Empty);
            var changeCommand = new ChangeBlockTypeCommand(block.BlockKey, blockType);

            // Create a composite command that binds everything together.
            var compositeCommand = new CompositeCommand<BlockCommandContext>(true, false);

            compositeCommand.Commands.Add(replaceCommand);
            compositeCommand.Commands.Add(changeCommand);

            // Add the command to the deferred execution so the command could
            // be properly handled via the undo/redo management.
            block.Project.Commands.DeferDo(compositeCommand);
        }
		internal void CommitItemFontSize(double? oldFontSize, double? newFontSize)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand("Change Items Font Size");

			foreach (var item in this.SelectedItems)
			{
				var ensureDifferentItem = item;
				var command = new UndoableDelegateCommand("Change Item Font Size",
					p =>
						{
							if (newFontSize.HasValue)
							{
								ensureDifferentItem.FontSize = newFontSize.Value;
							}
						},
					p =>
						{
							if (oldFontSize.HasValue)
							{
								ensureDifferentItem.FontSize = oldFontSize.Value;
							}
						});
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);
		}
		internal void CommitShapePositionY(double newPositionY)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand(CommandNames.MoveItems);

			foreach (var shape in this.SelectedShapes)
			{
				var ensureDifferentShape = shape;
				var ensureOldValue = ensureDifferentShape.Position.Y;
				var command = new UndoableDelegateCommand(CommandNames.MoveItem,
					p => ensureDifferentShape.Position = new Point(ensureDifferentShape.Position.X, newPositionY),
					p => ensureDifferentShape.Position = new Point(ensureDifferentShape.Position.X, ensureOldValue));
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);

			this.OnBoundsChanged();
		}
		private static void DetachConnections(RadDiagram diagram)
		{
			if (diagram.SelectedItems.Count() > 1)
			{
				CompositeCommand changeSourcesCompositeCommand = new CompositeCommand("Detach ends");
				foreach (var connection in diagram.SelectedItems.OfType<IConnection>())
				{
					if (!diagram.SelectedItems.Contains(connection.Source))
					{
						changeSourcesCompositeCommand.AddCommand(new ChangeSourceCommand(connection, null, connection.StartPoint));
					}

					if (!diagram.SelectedItems.Contains(connection.Target))
					{
						changeSourcesCompositeCommand.AddCommand(new ChangeTargetCommand(connection, null, connection.EndPoint));
					}
				}
				changeSourcesCompositeCommand.Execute();
				AttachedProperties.SetPendingCommand(diagram, changeSourcesCompositeCommand);
			}
		}
		internal void CommitShapeRotaionAngle(double newRotaionAngle)
		{
			if (this.owner == null)
			{
				return;
			}

			var compositeCommand = new CompositeCommand(CommandNames.RotateItems);

			foreach (var shape in this.SelectedShapes)
			{
				var ensureDifferentShape = shape;
				var ensureOldValue = ensureDifferentShape.RotationAngle;
				var command = new UndoableDelegateCommand(CommandNames.RotateItem,
					p => ensureDifferentShape.RotationAngle = newRotaionAngle,
					p => ensureDifferentShape.RotationAngle = ensureOldValue);
				compositeCommand.AddCommand(command);
			}

			this.owner.UndoRedoService.ExecuteCommand(compositeCommand);

			this.OnBoundsChanged();
		}
        private void AddContainer(MainContainerShapeBase container, IShape itemToAdd)
        {
            if (container == null || itemToAdd == null) return;
            CompositeCommand command = new CompositeCommand("Add new container");
            if (container.IsCollapsed)
            {
                command.AddCommand(new UndoableDelegateCommand("Update container",
                   new Action<object>((o) =>
                   {
                       container.IsCollapsed = false;
                   }),
                   new Action<object>((o) =>
                   {
                       container.IsCollapsed = true;
                   })));
            }
            command.AddCommand(new UndoableDelegateCommand("Add Container",
                  new Action<object>((o) =>
                  {
                      container.Items.Add(itemToAdd);
                      container.IsCollapsed = false;
                  }),
                  new Action<object>((o) =>
                  {
                      this.Diagram.RemoveShape(itemToAdd);
                      container.IsCollapsed = false;
                  })));

            this.Diagram.UndoRedoService.ExecuteCommand(command);
        }