示例#1
0
		public IEnumerable<IContextAction> GetAvailableActions(EditorContext context)
		{
			// re-initialize the context
			this.Context = context;
			if (this.IsAvailable(context))
				yield return this;
		}
 protected override Size CalculateEditorSize(EditorContext context)
 {
     if (Parent.HeaderStyle != ColumnHeaderStyle.None)
         return context.Bounds.Size;
     else
         return new Size(EditorWidth, context.Bounds.Height);
 }
		public void Initialize(EditorContext context)
		{
			// class at caret (either declaration of usage)
			this.Class = GetClass(context.CurrentSymbol);
			if (this.Class == null)
				return;
			var c = this.Class;
			
			// TODO cache
			var classDecls = context.GetClassDeclarationsOnCurrentLine().ToList();
			this.IsCaretAtClassDeclaration = classDecls.Count == 1 && (classDecls[0].FullyQualifiedName == c.FullyQualifiedName);
			
			this.IsClassFileNameCorrect = (c.IsInnerClass() || (!c.IsUserCode()) ||
			                               c.Name.Equals(Path.GetFileNameWithoutExtension(c.CompilationUnit.FileName), StringComparison.OrdinalIgnoreCase));
			
			if (string.IsNullOrEmpty(c.Name) || c.CompilationUnit == null || string.IsNullOrEmpty(c.CompilationUnit.FileName)) {
				// Cannot get path
				this.CorrectClassFileName = null;
				this.IsCorrectClassFileNameAvailable = false;
				return;
			}
			this.CorrectClassFileName = Path.Combine(Path.GetDirectoryName(c.CompilationUnit.FileName),
			                                    c.Name + Path.GetExtension(c.CompilationUnit.FileName));
			
			this.IsCorrectClassFileNameAvailable = (FileUtility.IsValidPath(CorrectClassFileName)
			                                        && Path.IsPathRooted(CorrectClassFileName)
			                                        && !File.Exists(CorrectClassFileName));
			
			this.IsClassReadOnly = FindReferencesAndRenameHelper.IsReadOnly(this.Class);
			
		}
示例#4
0
 protected override Size CalculateEditorSize(EditorContext context)
 {
     if (Parent.UseColumns)
     return context.Bounds.Size;
        else
     return new Size(EditorWidth, context.Bounds.Height);
 }
示例#5
0
		IEnumerable<IContextAction> GetAddUsingAttributeActions(EditorContext context)
		{
			ResolveResult symbol = context.CurrentSymbol;
			if (!(symbol is UnknownIdentifierResolveResult || symbol is UnknownMethodResolveResult))
				yield break;

			List<IClass> results = new List<IClass>();
			
			ParseInformation info = context.CurrentParseInformation;
			if (info == null || info.CompilationUnit == null || info.CompilationUnit.ProjectContent == null)
				yield break;
			ICompilationUnit unit = info.CompilationUnit;
			IProjectContent pc = info.CompilationUnit.ProjectContent;
			
			string name = null;
			if (symbol is UnknownMethodResolveResult) {
				name = Search((UnknownMethodResolveResult)symbol, pc, results);
			}
			if (symbol is UnknownIdentifierResolveResult) {
				name = Search((UnknownIdentifierResolveResult)symbol, pc, results);
			} else {
				yield break;
			}
			
			foreach (IClass c in results) {
				yield return new RefactoringService.AddUsingAction(unit, context.Editor, c.Namespace);
			}
		}
		public override void Execute(EditorContext context)
		{
			var cache = context.GetCached<CheckAssignmentCache>();
			
			var ifStatement = GenerateAstToInsert(cache.VariableName);
			context.Editor.InsertCodeAfter(cache.Element, ifStatement, true);
		}
示例#7
0
		public override void Execute(EditorContext context)
		{
			var paramAtCaret = GetParameterAtCaret(context);
			if (paramAtCaret != null)
			{
				Extensions.AddCodeToMethodStart(paramAtCaret.CallingMember, context.Editor, GetCodeToInsert(paramAtCaret.VariableName));
			}
		}
		public override void Execute(EditorContext context)
		{
			IProject project = (IProject)ClassAtCaret.Class.ProjectContent.Project;
			RefactoringHelpers.RenameFile(project, ClassAtCaret.Class.CompilationUnit.FileName, ClassAtCaret.CorrectClassFileName);
			if (project != null) {
				project.Save();
			}
		}
		public void SetEditorBounds(EditorContext context)
		{
			Size size = CalculateEditorSize(context);
			context.Editor.Bounds = new Rectangle(context.Bounds.X, context.Bounds.Y,
				Math.Min(size.Width, context.Bounds.Width),
				Math.Min(size.Height, Parent.ClientSize.Height - context.Bounds.Y)
			);
		}
		public override IEnumerable<IContextAction> GetAvailableActions(EditorContext editorContext)
		{
			foreach (var targetClass in editorContext.GetClassDeclarationsOnCurrentLine().Where(c => c.ClassType == ClassType.Class).Select(c2 => c2.GetCurrentClassPart(editorContext.Editor.FileName))) {
				foreach (var implementAction in RefactoringService.GetImplementAbstractClassActions(targetClass)) {
					yield return implementAction;
				}
			}
		}
示例#11
0
		public override bool IsAvailable(EditorContext context)
		{
			var paramAtCaret = GetParameterAtCaret(context.CurrentSymbol);
			if (paramAtCaret == null)
				return false;
			
			return IsAvailable(paramAtCaret.ResolvedType);
		}
示例#12
0
		public void Initialize(EditorContext context)
		{
			this.context = context;
			this.VariableName = GetVariableName(context);
			this.CodeGenerator = GetCodeGenerator(context);
			this.Element = GetElement(context);
			this.ElementRegion = (Element == null) ? DomRegion.Empty : DomRegion.FromLocation(Element.StartLocation, Element.EndLocation);
		}
示例#13
0
		public override void Execute(EditorContext context)
		{
			var conditionExpr = BuildCondition(this.targetExpr);
			if (conditionExpr == null)
				return;
			var ifExpr = new IfElseStatement(conditionExpr, new BlockStatement());
			
			context.Editor.InsertCodeBefore(this.currentExpr, ifExpr);
		}
示例#14
0
		protected override Size CalculateEditorSize(EditorContext context)
		{
			if (Parent.UseColumns)
				return context.Bounds.Size;
			else
			{
				Size size = GetLabelSize(context.CurrentNode, context.DrawContext, _label);
				int width = Math.Max(size.Width + Font.Height, MinTextBoxWidth); // reserve a place for new typed character
				return new Size(width, size.Height);
			}
		}
		public override void Execute(EditorContext context)
		{
			var cache = context.GetCached<CheckAssignmentCache>();
			
			var ifStatement = GenerateAstToInsert(cache.VariableName);

			var editor = context.Editor;
			string indent = DocumentUtilitites.GetWhitespaceAfter(editor.Document, editor.Document.GetLineStartOffset(cache.ElementRegion.GetStart()));
			string code = cache.CodeGenerator.GenerateCode(ifStatement, indent);
			int insertOffset = editor.Document.GetLineEndOffset(cache.ElementRegion.GetEnd());
			editor.Document.Insert(insertOffset, code);
			editor.Caret.Offset = insertOffset + code.Length - 1;
		}
示例#16
0
		public override IEnumerable<IContextAction> GetAvailableActions(EditorContext editorContext)
		{
			// Using CurrentLineAST is basically OK, but when the "class" keyword is on different line than class name,
			// parsing only one line never tells us that we are looking at TypeDeclaration
			// Alternative solution could be to try to resolve also IdentifierExpression to see if it is class declaration.
			foreach (var targetClass in editorContext.GetClassDeclarationsOnCurrentLine()
			         .Where(c => c.ClassType == ClassType.Class || c.ClassType == ClassType.Interface)
			         .Select(c2 => c2.GetCurrentClassPart(editorContext.Editor.FileName))) {
				foreach (var implementAction in RefactoringService.GetImplementInterfaceActions(targetClass)) {
					yield return implementAction;
				}
			}
		}
示例#17
0
		protected string GetVariableName(EditorContext context)
		{
			// a = Foo()      : AssignmentExpression.Left == IdentifierExpression(*identifier*)
			// var a = Foo()  : VariableDeclaration(*name*).Initializer != empty
			var variableName = GetVariableNameFromAssignment(context.GetContainingElement<AssignmentExpression>());
			if (variableName != null)
				return variableName;
			variableName = GetVariableNameFromVariableDeclaration(context.GetContainingElement<LocalVariableDeclaration>());
			if (variableName != null)
				return variableName;
			
			return null;
		}
示例#18
0
		protected AbstractNode GetElement(EditorContext context)
		{
			// a = Foo()      : AssignmentExpression.Left == IdentifierExpression(*identifier*)
			// var a = Foo()  : VariableDeclaration(*name*).Initializer != empty
			var assignment = context.GetContainingElement<AssignmentExpression>();
			if (assignment != null)
				return assignment;
			var declaration = context.GetContainingElement<LocalVariableDeclaration>();
			if (declaration != null)
				return declaration;
			
			return null;
		}
		protected DomRegion GetStatementRegion(EditorContext context)
		{
			// a = Foo()      : AssignmentExpression.Left == IdentifierExpression(*identifier*)
			// var a = Foo()  : VariableDeclaration(*name*).Initializer != empty
			
			var assignment = context.GetContainingElement<AssignmentExpression>();
			if (assignment != null)
				return DomRegion.FromLocation(assignment.StartLocation, assignment.EndLocation);
			var declaration = context.GetContainingElement<LocalVariableDeclaration>();
			if (declaration != null)
				return DomRegion.FromLocation(declaration.StartLocation, declaration.EndLocation);
			
			return DomRegion.Empty;
		}
		public EditorActionsProvider(ITextEditor editor, IList<IContextActionsProvider> providers)
		{
			if (editor == null)
				throw new ArgumentNullException("editor");
			if (providers == null)
				throw new ArgumentNullException("providers");
			this.editor = editor;
			this.providers = providers;
			// DO NOT USE Wait on the main thread!
			// causes deadlocks!
			// parseTask.Wait();
			// Reparse so that we have up-to-date DOM.
			ParserService.ParseCurrentViewContent();
			this.EditorContext = new EditorContext(editor);
		}
		public void SetEditorBounds(EditorContext context)
		{
			Size size=CalculateEditorSize(context);

			int yPos=context.Bounds.Y+context.Bounds.Height/2-(size.Height/2)-1; //Editor auf Y Achse zentrieren

			context.Editor.Bounds=new Rectangle(context.Bounds.X, yPos,
			Math.Min(size.Width, context.Bounds.Width),
			Math.Min(size.Height, Parent.ClientSize.Height-context.Bounds.Y)
			);

			//context.Editor.Bounds=new Rectangle(context.Bounds.X, context.Bounds.Y,
			//    Math.Min(size.Width, context.Bounds.Width),
			//    Math.Min(size.Height, Parent.ClientSize.Height-context.Bounds.Y)
			//);
		}
示例#22
0
 protected override Size CalculateEditorSize(EditorContext context)
 {
     if (Parent.UseColumns)
     {
         if (context.Editor is CheckedListBox)
             return new Size(context.Bounds.Size.Width, EditorHeight);
         else
             return context.Bounds.Size;
     }
     else
     {
         if (context.Editor is CheckedListBox)
             return new Size(EditorWidth, EditorHeight);
         else
             return new Size(EditorWidth, context.Bounds.Height);
     }
 }
示例#23
0
文件: Program.cs 项目: hacklex/Core2D
        static void CreateProjectUsingContext()
        {
            var context = new EditorContext()
            {
                ProjectFactory = new ProjectFactory(),
                Serializer = new NewtonsoftSerializer()
            };

            var project = context.ProjectFactory.GetProject();
            context.Editor = Editor.Create(project, null, false, false);

            var factory = new ShapeFactory(context.Editor);
            factory.Line(30, 30, 60, 30);
            factory.Text(30, 30, 60, 60, "Sample1");

            context.Save("sample1.project");
        }
示例#24
0
 /// <summary>
 /// Auto save docking manager layout.
 /// </summary>
 /// <param name="context"></param>
 public void AutoSaveLayout(EditorContext context)
 {
     try
     {
         SaveLayout(_defaultLayoutFileName);
     }
     catch (Exception ex)
     {
         if (context.Editor.Log != null)
         {
             context.Editor.Log.LogError("{0}{1}{2}",
                 ex.Message,
                 Environment.NewLine,
                 ex.StackTrace);
         }
     }
 }
		public override void Execute(EditorContext context)
		{
			var cache = context.GetCached<CheckAssignmentCache>();
			
			var ifStatement = GenerateAstToInsert(cache.VariableName);
			
			var editor = context.Editor;
			var doc = editor.Document;
			
			using (var undoGroup = editor.Document.OpenUndoGroup()) {
				editor.InsertCodeAfter(cache.Element, ifStatement);
				// set caret to the position of the special marker
				var caretPos = doc.Text.IndexOf(caretMarker, doc.GetLineEndOffset(cache.Element.EndLocation));
				editor.Caret.Offset = caretPos;
				editor.Document.RemoveRestOfLine(caretPos);
			}
		}
		public override void Execute(EditorContext context)
		{
			var cache = context.GetCached<CheckAssignmentCache>();
			
			var ifStatement = GenerateAstToInsert(cache.VariableName);
			
			var editor = context.Editor;
			string indent = DocumentUtilitites.GetWhitespaceAfter(editor.Document, editor.Document.GetLineStartOffset(cache.ElementRegion.GetStart()));
			string code = cache.CodeGenerator.GenerateCode(ifStatement, indent);
			int insertOffset = editor.Document.GetLineEndOffset(cache.ElementRegion.GetEnd());
			using (var undoGroup = editor.Document.OpenUndoGroup()) {
				editor.Document.Insert(insertOffset, code);
				var caretPos = editor.Document.Text.IndexOf(caretMarker, insertOffset);
				editor.Caret.Offset = caretPos;
				editor.Document.RemoveRestOfLine(caretPos);
			}
		}
示例#27
0
		IEnumerable<IContextAction> GetAddUsingExtensionMethodActions(EditorContext context)
		{
			UnknownMethodResolveResult rr = context.CurrentSymbol as UnknownMethodResolveResult;
			if (rr == null)
				yield break;
			
			List<IClass> results = new List<IClass>();
			IProjectContent pc = context.ProjectContent;
			
			SearchAllExtensionMethodsWithName(results, pc, rr.CallName);
			foreach (IProjectContent content in pc.ReferencedContents)
				SearchAllExtensionMethodsWithName(results, content, rr.CallName);
			
			foreach (IClass c in results) {
				yield return new RefactoringService.AddUsingAction(context.CurrentParseInformation.CompilationUnit, context.Editor, c.Namespace);
			}
		}
示例#28
0
		public override bool IsAvailable(EditorContext context)
		{
			this.currentExpr = context.GetContainingElement<Expression>();
			if (currentExpr is InvocationExpression) {
				// InvocationExpression (e.g. "e.Foo()") has MemberReferenceExpression as TargetObject (e.g. "e.Foo")
				// "e.Foo() -> e"
				this.targetExpr = GetTarget(((InvocationExpression)currentExpr).TargetObject);
			} else {
				// "a.b" -> "a"
				this.targetExpr = GetTarget(currentExpr);
			}
			return 
				this.targetExpr is MemberReferenceExpression ||
				this.targetExpr is CastExpression ||
				this.targetExpr is ParenthesizedExpression;
				//this.targetExpr is IdentifierExpression;		// "don't offer the action for just a.b, only for a.b.c"
		}
示例#29
0
		public LocalResolveResult GetParameterAtCaret(EditorContext context)
		{
			LocalResolveResult paramAtCaret = context.CurrentSymbol as LocalResolveResult;
			if (paramAtCaret == null || paramAtCaret.CallingClass == null || paramAtCaret.ResolvedType == null)
				return null;
			// only for C#
			if (paramAtCaret.CallingClass.ProjectContent.Language != LanguageProperties.CSharp)
				return null;
			if (!paramAtCaret.IsParameter)
				return null;
			// must be definition
			if (!paramAtCaret.VariableDefinitionRegion.IsInside(context.CurrentExpression.Region.BeginLine, context.CurrentExpression.Region.BeginColumn))
				return null;
			// must be not abstract/interface method
			if (paramAtCaret.CallingMember == null || paramAtCaret.CallingMember.IsAbstract || 
			    paramAtCaret.CallingMember.DeclaringType.ClassType == ClassType.Interface)
				return null;
			return paramAtCaret;
		}
示例#30
0
		public override IEnumerable<IContextAction> GetAvailableActions(EditorContext context)
		{
			if (string.IsNullOrEmpty(context.CurrentExpression.Expression)) {
				yield break;
			}
			if (context.CurrentExpression.Region != null && 
			    context.CurrentExpression.Region.EndLine > context.CurrentExpression.Region.BeginLine) {
				// do not yield the action for 2-line expressions like this, which are actually 2 different expressions
				//   variable.(*caret*)
				//   CallFooMethod();
				// this check is not correct for this case because it does not yield the action when it should:
				//   variable.Foo((*caret*)
				//                123);
				yield break;
			}
			var generateCodeAction = GenerateCode.GetContextAction(context);
			if (generateCodeAction != null)
				yield return generateCodeAction;
		}
示例#31
0
 public void AfterScenario()
 {
     Context.RemoveMessages();
     Context = null;
 }
示例#32
0
 public void Redo()
 {
     EditorContext.Redo();
 }
示例#33
0
 public BaseSliderComponent(EditorContext context, string tag) : base(context, tag)
 {
 }
示例#34
0
 public void Save()
 {
     EditorContext.Save();
 }
        private async void HandlePSEventReceivedAsync(object sender, PSEventArgs args)
        {
            if (string.Equals(RemoteSessionOpenFile, args.SourceIdentifier, StringComparison.CurrentCultureIgnoreCase))
            {
                try
                {
                    if (args.SourceArgs.Length >= 1)
                    {
                        string localFilePath  = string.Empty;
                        string remoteFilePath = args.SourceArgs[0] as string;

                        // Is this a local process runspace?  Treat as a local file
                        if (this.powerShellContext.CurrentRunspace.Location == RunspaceLocation.Local)
                        {
                            localFilePath = remoteFilePath;
                        }
                        else
                        {
                            byte[] fileContent = null;

                            if (args.SourceArgs.Length >= 2)
                            {
                                // Try to cast as a PSObject to get the BaseObject, if not, then try to case as a byte[]
                                PSObject sourceObj = args.SourceArgs[1] as PSObject;
                                if (sourceObj != null)
                                {
                                    fileContent = sourceObj.BaseObject as byte[];
                                }
                                else
                                {
                                    fileContent = args.SourceArgs[1] as byte[];
                                }
                            }

                            // If fileContent is still null after trying to
                            // unpack the contents, just return an empty byte
                            // array.
                            fileContent = fileContent ?? new byte[0];

                            if (remoteFilePath != null)
                            {
                                localFilePath =
                                    this.StoreRemoteFile(
                                        remoteFilePath,
                                        fileContent,
                                        this.powerShellContext.CurrentRunspace);
                            }
                            else
                            {
                                await this.editorOperations?.NewFileAsync();

                                EditorContext context = await this.editorOperations?.GetEditorContextAsync();

                                context?.CurrentFile.InsertText(Encoding.UTF8.GetString(fileContent, 0, fileContent.Length));
                            }
                        }

                        bool preview = true;
                        if (args.SourceArgs.Length >= 3)
                        {
                            bool?previewCheck = args.SourceArgs[2] as bool?;
                            preview = previewCheck ?? true;
                        }

                        // Open the file in the editor
                        this.editorOperations?.OpenFileAsync(localFilePath, preview);
                    }
                }
                catch (NullReferenceException e)
                {
                    this.logger.LogException("Could not store null remote file content", e);
                }
            }
        }
示例#36
0
 public void Undo()
 {
     EditorContext.Undo();
 }
示例#37
0
        protected override void OnLoad(EventArgs e)
        {
            Parent.Dock = DockStyle.Fill;

            Form form = FindForm();

            form.AcceptButton = buttonOK;
            form.CancelButton = buttonCancel;
            form.MinimumSize  = new Size(536, 320);
            form.ShowIcon     = false;
            //form.MaximizeBox = true;
            form.Closing += delegate
            {
                if (form.DialogResult == DialogResult.Cancel)
                {
                    originalState.Restore();
                    EditorContext.ApplyDecorator();
                }
                else
                {
                    // This forces the linked image to be updated as well
                    SaveSettingsAndApplyDecorator();
                }
            };

            base.OnLoad(e);

            if (EditorContext.EnforcedAspectRatio == null)
            {
                int width = cbAspectRatio.Left - lblAspectRatio.Right;

                DisplayHelper.AutoFitSystemLabel(lblAspectRatio, 0, int.MaxValue);

                DisplayHelper.AutoFitSystemCombo(cbAspectRatio, 0, int.MaxValue, false);
                buttonRotate.Width = buttonRotate.GetPreferredWidth();

                bool isButtonRotateVisible = buttonRotate.Visible;
                buttonRotate.Visible = true;
                LayoutHelper.DistributeHorizontally(width, lblAspectRatio, cbAspectRatio, buttonRotate);
                buttonRotate.Visible = isButtonRotateVisible;
                if (isButtonRotateVisible && (cbAspectRatio.Height + 2) > buttonRotate.Height)
                {
                    buttonRotate.Height = cbAspectRatio.Height + 2;
                }
            }
            else
            {
                lblAspectRatio.Visible       =
                    cbAspectRatio.Visible    =
                        buttonRotate.Visible = false;
            }

            DisplayHelper.AutoFitSystemCheckBox(chkGrid, 0, int.MaxValue);
            DisplayHelper.AutoFitSystemButton(btnRemoveCrop);
            LayoutHelper.FixupOKCancel(buttonOK, buttonCancel);
            chkGrid.Left = buttonCancel.Right - chkGrid.Width;

            panel1.Height        = Math.Max(buttonRotate.Bottom, cbAspectRatio.Bottom) + 3;
            imageCropControl.Top = panel1.Bottom;

            imageCropControl.Select();

            //int minWidth = buttonRotate.Right + width + (form.ClientSize.Width - buttonOK.Left) + SystemInformation.FrameBorderSize.Width * 2;
            //form.MinimumSize = new Size(minWidth, form.MinimumSize.Height);
        }
示例#38
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="context"></param>
 public ZoomState(EditorContext context)
 {
     _context = context;
 }
示例#39
0
 private void RefreshUndoRedoButtons()
 {
     undoButton.interactable = EditorContext.CanUndo();
     redoButton.interactable = EditorContext.CanRedo();
 }
示例#40
0
        public override bool IsAvailable(EditorContext context)
        {
            var cache = context.GetCached <CheckAssignmentCache>();

            return(cache.IsActionAvailable);
        }
示例#41
0
 public void BeforeScenario()
 {
     Context = new EditorContext();
 }
示例#42
0
 public HostComponent(VisualElement element, EditorContext ctx) : base(element, ctx, "_root")
 {
 }
        public async Task <IActionResult> Get([FromServices] EditorContext context)
        {
            var entries = new List <ChangeFeedEntry>();
            await context
            .RoadNetworkChanges
            .OrderByDescending(_ => _.Id)
            .ForEachAsync(change =>
            {
                var when      = InstantPattern.ExtendedIso.Parse(change.When).GetValueOrThrow();
                var localWhen = when.InZone(_localTimeZone).LocalDateTime;
                var item      = new ChangeFeedEntry
                {
                    Id        = change.Id,
                    Title     = change.Title,
                    Type      = change.Type,
                    Day       = localWhen.Day.ToString("00"),
                    Month     = _localMonthPattern.Format(localWhen.Date),
                    TimeOfDay = _localTimeOfDayPattern.Format(localWhen.TimeOfDay)
                };
                switch (change.Type)
                {
                case nameof(BeganRoadNetworkImport):
                    item.Content = null;
                    break;

                case nameof(CompletedRoadNetworkImport):
                    item.Content = null;
                    break;

                case nameof(RoadNetworkChangesArchiveUploaded):
                    item.Content = JsonConvert.DeserializeObject(change.Content,
                                                                 typeof(RoadNetworkChangesArchiveUploadedEntry));
                    break;

                case nameof(RoadNetworkChangesArchiveAccepted):
                    item.Content = JsonConvert.DeserializeObject(change.Content,
                                                                 typeof(RoadNetworkChangesArchiveAcceptedEntry));
                    break;

                case nameof(RoadNetworkChangesArchiveRejected):
                    item.Content = JsonConvert.DeserializeObject(change.Content,
                                                                 typeof(RoadNetworkChangesArchiveRejectedEntry));
                    break;

                case nameof(RoadNetworkChangesBasedOnArchiveAccepted):
                    item.Content = JsonConvert.DeserializeObject(change.Content,
                                                                 typeof(RoadNetworkChangesBasedOnArchiveAcceptedEntry));
                    break;

                case nameof(RoadNetworkChangesBasedOnArchiveRejected):
                    item.Content = JsonConvert.DeserializeObject(change.Content,
                                                                 typeof(RoadNetworkChangesBasedOnArchiveRejectedEntry));
                    break;
                }

                entries.Add(item);
            }, HttpContext.RequestAborted);

            return(new JsonResult(new ChangeFeedResponse
            {
                Entries = entries.ToArray()
            })
            {
                StatusCode = StatusCodes.Status200OK
            });
        }
示例#44
0
        // could work to extend selection to set of adjacent statements - e.g. select 3 lines
        static Selection ExtendSelection(ITextEditor editor, CompilationUnit parsedCU, IList <ISpecial> commentsBlankLines, out INode selectedResultNode, Type[] interestingNodeTypes)
        {
            selectedResultNode = null;

            var selectionStart = editor.Document.OffsetToPosition(editor.SelectionStart);
            var selectionEnd   = editor.Document.OffsetToPosition(editor.SelectionStart + editor.SelectionLength);

            Ast.INode currentNode = parsedCU.Children.Select(
                n => EditorContext.FindInnermostNodeContainingSelection(n, selectionStart, selectionEnd)).Where(n => n != null).FirstOrDefault();
            if (currentNode == null)
            {
                return(null);
            }
            if (!IsNodeTypeInteresting(currentNode, interestingNodeTypes))
            {
                // ignore uninteresting nodes in the AST
                currentNode = GetInterestingParent(currentNode, interestingNodeTypes);
            }
            if (currentNode == null)
            {
                return(null);
            }
            selectedResultNode = currentNode;

            // whole node already selected -> expand selection
            if (currentNode.StartLocation == selectionStart && currentNode.EndLocation == selectionEnd)
            {
                // selected node stays the same
                var selectionExtendedToComments = ExtendSelectionToComments(editor.Document, selectionStart, selectionEnd, commentsBlankLines);
                if (selectionExtendedToComments != null)
                {
                    // Can be extended to comments -> extend
                    selectionStart = selectionExtendedToComments.Start;
                    selectionEnd   = selectionExtendedToComments.End;
                }
                else
                {
                    var parent = GetInterestingParent(currentNode, interestingNodeTypes);
                    // it can happen that parent region exactly matches child region - in this case we need to advance even to the next parent
                    // bc otherwise the selection would never move
                    while (parent != null && parent.StartLocation == selectionStart && parent.EndLocation == selectionEnd)
                    {
                        parent = GetInterestingParent(parent, interestingNodeTypes);
                    }
                    if (parent == null)
                    {
                        return(new Selection {
                            Start = selectionStart, End = selectionEnd
                        });
                    }
                    // Select the parent
                    var extendedSelectionStart = parent.StartLocation;
                    var extendedLocationEnd    = parent.EndLocation;
                    selectedResultNode = parent;

                    // if the extended selection would contain blank lines, extend the selection only to the blank lines/comments on both sides (use siblings)
                    //   if the selection contains blank lines or comments on both sides, dont do this
                    var blankLines = commentsBlankLines.Where(s => s is BlankLine).Cast <BlankLine>().ToList();
                    //if (SelectionContainsBlankLines(extendedSelectionStart, extendedLocationEnd, blankLines)) {
                    if (false)                       // implement later

                    {
                    }
                    else
                    {
                        selectionStart = extendedSelectionStart;
                        selectionEnd   = extendedLocationEnd;
                    }
                }
            }
            else
            {
                // select current node
                selectionStart     = currentNode.StartLocation;
                selectionEnd       = currentNode.EndLocation;
                selectedResultNode = currentNode;
            }
            return(new Selection {
                Start = selectionStart, End = selectionEnd
            });
        }
示例#45
0
 public SaveToPdfHandler(Invoker invoker, Shortcut shortcut, EditorContext editorContext) : base(invoker, shortcut)
 {
     _editorContext = editorContext;
 }
 public Task InvokeCommandAsync(string commandName, EditorContext editorContext) => _extensionService.InvokeCommandAsync(commandName, editorContext, CancellationToken.None);
 public Task InvokeCommandAsync(string commandName, EditorContext editorContext) => _extensionService.InvokeCommandAsync(commandName, editorContext);
示例#48
0
 public EditorsController(EditorContext context)
 {
     _context = context;
 }
示例#49
0
 public XmlElementComment(System.Xml.XmlNode xmlNode, XmlEditor xmlEditor, EditorContext editorContext) : base(xmlNode, xmlEditor, editorContext)
 {
 }
示例#50
0
 protected abstract Size CalculateEditorSize(EditorContext context);
示例#51
0
 /// <summary>
 ///
 /// </summary>
 /// <param name="context"></param>
 /// <param name="invalidate"></param>
 public ZoomState(EditorContext context, Action invalidate)
 {
     _context    = context;
     _invalidate = invalidate;
 }
示例#52
0
 public AnchorComponent(EditorContext context) : base(context, "anchor")
 {
     Element.clicked += LinkClicked;
 }
示例#53
0
 public TextComponent(string text, EditorContext context, string tag) : base(context, tag)
 {
     Element.text = text;
 }
示例#54
0
 public Task WriteAsync(ZipArchive archive, EditorContext context, CancellationToken cancellationToken)
 {
     return(_writer.WriteAsync(archive, context, cancellationToken));
 }
示例#55
0
        /// <summary>
        /// Grabs HTML copied in the clipboard and pastes it into the document (pulls in a copy of embedded content too)
        /// </summary>
        protected override bool DoInsertData(DataAction action, MarkupPointer begin, MarkupPointer end)
        {
            using (new WaitCursor())
            {
                try
                {
                    string baseUrl = UrlHelper.GetBasePathUrl(DataMeister.HTMLData.SourceURL);
                    string html    = DataMeister.HTMLData.HTMLSelection;

                    //Check to see if the selection has an incomplete unordered list
                    var finder = new IncompleteListFinder(html);
                    finder.Parse();

                    if ((!EditorContext.CleanHtmlOnPaste) || finder.HasIncompleteList)
                    {
                        using (IUndoUnit undoUnit = EditorContext.CreateInvisibleUndoUnit())
                        {
                            // Create a new MarkupContainer off of EditorContext's document that contains the source HTML
                            // with comments marking the start and end selection.
                            MarkupContainer sourceContainer = EditorContext.MarkupServices.ParseString(DataMeister.HTMLData.HTMLWithMarkers);

                            // MSHTML's ParseString implementation clears all the attributes on the <body> element, so we
                            // have to manually add them back in.
                            CopyBodyAttributes(DataMeister.HTMLData.HTMLWithMarkers, sourceContainer.Document.body);

                            MarkupRange sourceRange = FindMarkedFragment(sourceContainer.Document,
                                                                         HTMLDataObject.START_FRAGMENT_MARKER, HTMLDataObject.END_FRAGMENT_MARKER);
                            MshtmlMarkupServices sourceContainerMarkupServices =
                                new MshtmlMarkupServices((IMarkupServicesRaw)sourceContainer.Document);

                            // Some applications may not add the correct fragment markers (e.g. copying from Fiddler from
                            // the Web Sessions view). We'll just select the entire <body> of the clipboard in this case.
                            if (sourceRange == null)
                            {
                                sourceRange = sourceContainerMarkupServices.CreateMarkupRange(sourceContainer.Document.body, false);
                            }
                            else
                            {
                                // Make sure that we don't try to copy just parts of a table/list. We need to include the
                                // parent table/list.
                                if (!EditorContext.CleanHtmlOnPaste)
                                {
                                    ExpandToIncludeTables(sourceRange, sourceContainerMarkupServices);
                                }
                                ExpandToIncludeLists(sourceRange, sourceContainerMarkupServices);
                            }

                            if (sourceRange != null)
                            {
                                if (!EditorContext.CleanHtmlOnPaste)
                                {
                                    // WinLive 273280: Alignment on a table acts like a float, which can throw off the layout of the rest of
                                    // the document. If there is nothing before or after the table, then we can safely remove the alignment.
                                    RemoveAlignmentIfSingleTable(sourceRange);

                                    // Serialize the source HTML to a string while keeping the source formatting.
                                    MarkupRange destinationRange = EditorContext.MarkupServices.CreateMarkupRange(begin.Clone(), end.Clone());
                                    html = KeepSourceFormatting(sourceRange, destinationRange);
                                }
                                else
                                {
                                    html = sourceRange.HtmlText;
                                }
                            }

                            undoUnit.Commit();
                        }

                        Trace.Assert(html != null, "Inline source CSS failed!");
                    }

                    if (html == null)
                    {
                        html = DataMeister.HTMLData.HTMLSelection;
                    }

                    if (IsPasteFromSharedCanvas(DataMeister))
                    {
                        if (action == DataAction.Copy)
                        {
                            // WinLive 96840 - Copying and pasting images within shared canvas should persist source
                            // decorator settings. "wlCopySrcUrl" is inserted while copy/pasting within canvas.
                            html = EditorContext.FixImageReferences(ImageCopyFixupHelper.FixupSourceUrlForCopy(html),
                                                                    DataMeister.HTMLData.SourceURL);
                        }
                    }
                    else
                    {
                        html = EditorContext.FixImageReferences(html, DataMeister.HTMLData.SourceURL);

                        HtmlCleanupRule cleanupRule = HtmlCleanupRule.Normal;
                        if (IsOfficeHtml(DataMeister.HTMLData))
                        {
                            cleanupRule = HtmlCleanupRule.PreserveTables;
                        }

                        // In Mail, we want to preserve the style of the html that is on the clipboard
                        // Whereas in Writer we by default want to remove formatting so it looks like your blog theme
                        if (EditorContext.CleanHtmlOnPaste)
                        {
                            // optionally cleanup the html
                            html = EditorContext.HtmlGenerationService.CleanupHtml(html, baseUrl, cleanupRule);
                        }
                        else
                        {
                            html = HtmlCleaner.StripNamespacedTagsAndCommentsAndMarkupDirectives(html);
                        }

                        // standard fixups
                        html = EditorContext.HtmlGenerationService.GenerateHtmlFromHtmlFragment(html, baseUrl);
                    }

                    // insert the content
                    if (EditorContext.MarshalHtmlSupported)
                    {
                        EditorContext.InsertHtml(begin, end, html, DataMeister.HTMLData.SourceURL);
                    }
                    else if (EditorContext.MarshalTextSupported)
                    {
                        // This is called only in the case that we're attempting to marshal HTML, but only
                        // text is supported. In this case, we should down convert to text and provide that.
                        html = HTMLDocumentHelper.HTMLToPlainText(html);
                        EditorContext.InsertHtml(begin, end, html, DataMeister.HTMLData.SourceURL);
                    }
                    else
                    {
                        Debug.Assert(false, "Html being inserted when text or html isn't supported.");
                    }

                    // Now select what was just inserted
                    EditorContext.MarkupServices.CreateMarkupRange(begin, end).ToTextRange().select();

                    //place the caret at the end of the inserted content
                    //EditorContext.MoveCaretToMarkupPointer(end, true);
                    return(true);
                }
                catch (Exception e)
                {
                    //bugfix 1696, put exceptions into the trace log.
                    Trace.Fail("Exception while inserting HTML: " + e.Message, e.StackTrace);
                    return(false);
                }
            }
        }
        public async Task WriteAsync(ZipArchive archive, EditorContext context, CancellationToken cancellationToken)
        {
            if (archive == null)
            {
                throw new ArgumentNullException(nameof(archive));
            }
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            var count = await context.RoadNodes.CountAsync(cancellationToken);

            var dbfEntry  = archive.CreateEntry("Wegknoop.dbf");
            var dbfHeader = new DbaseFileHeader(
                DateTime.Now,
                DbaseCodePage.Western_European_ANSI,
                new DbaseRecordCount(count),
                RoadNodeDbaseRecord.Schema
                );

            using (var dbfEntryStream = dbfEntry.Open())
                using (var dbfWriter =
                           new DbaseBinaryWriter(
                               dbfHeader,
                               new BinaryWriter(dbfEntryStream, _encoding, true)))
                {
                    var dbfRecord = new RoadNodeDbaseRecord();
                    foreach (var data in context.RoadNodes.OrderBy(_ => _.Id).Select(_ => _.DbaseRecord))
                    {
                        dbfRecord.FromBytes(data, _manager, _encoding);
                        dbfWriter.Write(dbfRecord);
                    }
                    dbfWriter.Writer.Flush();
                    await dbfEntryStream.FlushAsync(cancellationToken);
                }

            var shpBoundingBox =
                (await context.RoadNodeBoundingBox.SingleOrDefaultAsync(cancellationToken))?.ToBoundingBox3D()
                ?? new BoundingBox3D(0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0);
            var info = await context.RoadNetworkInfo.SingleAsync(cancellationToken);

            var shpEntry  = archive.CreateEntry("Wegknoop.shp");
            var shpHeader = new ShapeFileHeader(
                new WordLength(info.TotalRoadNodeShapeLength),
                ShapeType.Point,
                shpBoundingBox);

            using (var shpEntryStream = shpEntry.Open())
                using (var shpWriter =
                           new ShapeBinaryWriter(
                               shpHeader,
                               new BinaryWriter(shpEntryStream, _encoding, true)))
                {
                    var number = RecordNumber.Initial;
                    foreach (var data in context.RoadNodes.OrderBy(_ => _.Id).Select(_ => _.ShapeRecordContent))
                    {
                        shpWriter.Write(
                            ShapeContentFactory
                            .FromBytes(data, _manager, _encoding)
                            .RecordAs(number)
                            );
                        number = number.Next();
                    }
                    shpWriter.Writer.Flush();
                    await shpEntryStream.FlushAsync(cancellationToken);
                }

            var shxEntry  = archive.CreateEntry("Wegknoop.shx");
            var shxHeader = shpHeader.ForIndex(new ShapeRecordCount(count));

            using (var shxEntryStream = shxEntry.Open())
                using (var shxWriter =
                           new ShapeIndexBinaryWriter(
                               shxHeader,
                               new BinaryWriter(shxEntryStream, _encoding, true)))
                {
                    var offset = ShapeIndexRecord.InitialOffset;
                    var number = RecordNumber.Initial;
                    foreach (var data in context.RoadNodes.OrderBy(_ => _.Id).Select(_ => _.ShapeRecordContent))
                    {
                        var shpRecord = ShapeContentFactory
                                        .FromBytes(data, _manager, _encoding)
                                        .RecordAs(number);
                        shxWriter.Write(shpRecord.IndexAt(offset));
                        number = number.Next();
                        offset = offset.Plus(shpRecord.Length);
                    }
                    shxWriter.Writer.Flush();
                    await shxEntryStream.FlushAsync(cancellationToken);
                }
        }
示例#57
0
 public ImageComponent(EditorContext context, string tag) : base(context, tag)
 {
 }
示例#58
0
 /// <summary>
 /// Initializes a new instance of the Factory class.
 /// </summary>
 /// <param name="context"></param>
 public Factory(EditorContext context)
 {
     Context = context;
 }
示例#59
0
 /// <summary>
 ///   Constructs a new factory for creating inspector controls.
 /// </summary>
 /// <param name="editorContext">Editor context the controls live in.</param>
 /// <param name="localizationContext">Context for localizing inspector values. <c>null</c> renders created controls unable to localize values.</param>
 public InspectorFactory(EditorContext editorContext, LocalizationContext localizationContext)
 {
     this.editorContext       = editorContext;
     this.localizationContext = localizationContext;
 }