⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 xmlview.cs

📁 c#源代码
💻 CS
📖 第 1 页 / 共 2 页
字号:
		#endregion
			
		#region IMementoCapable interface
		
		public void SetMemento(IXmlConvertable memento)
		{
			IProperties properties = (IProperties)memento;
			string[] bookMarks = properties.GetProperty("Bookmarks").ToString().Split(',');
			foreach (string mark in bookMarks) {
				if (mark != null && mark.Length > 0) {
					xmlEditor.Document.BookmarkManager.Marks.Add(Int32.Parse(mark));
				}
			}
			
			xmlEditor.ActiveTextAreaControl.Caret.Position =  xmlEditor.Document.OffsetToPosition(Math.Min(xmlEditor.Document.TextLength, Math.Max(0, properties.GetProperty("CaretOffset", xmlEditor.ActiveTextAreaControl.Caret.Offset))));

			if (xmlEditor.Document.HighlightingStrategy.Name != properties.GetProperty("HighlightingLanguage", xmlEditor.Document.HighlightingStrategy.Name)) {
				IHighlightingStrategy highlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy(properties.GetProperty("HighlightingLanguage", xmlEditor.Document.HighlightingStrategy.Name));
				if (highlightingStrategy != null) {
					xmlEditor.Document.HighlightingStrategy = highlightingStrategy;
				}
			}
			xmlEditor.ActiveTextAreaControl.TextArea.TextView.FirstVisibleLine = properties.GetProperty("VisibleLine", 0);
			
			xmlEditor.Document.FoldingManager.DeserializeFromString(properties.GetProperty("Foldings", ""));		
		}
		
		public IXmlConvertable CreateMemento()
		{
			DefaultProperties properties = new DefaultProperties();
			string[] bookMarks = new string[xmlEditor.Document.BookmarkManager.Marks.Count];
			for (int i = 0; i < bookMarks.Length; ++i) {
				bookMarks[i] = xmlEditor.Document.BookmarkManager.Marks[i].ToString();
			}
			properties.SetProperty("Bookmarks",   String.Join(",", bookMarks));
			properties.SetProperty("CaretOffset", xmlEditor.ActiveTextAreaControl.Caret.Offset);
			properties.SetProperty("VisibleLine", xmlEditor.ActiveTextAreaControl.TextArea.TextView.FirstVisibleLine);
			properties.SetProperty("HighlightingLanguage", xmlEditor.Document.HighlightingStrategy.Name);
			properties.SetProperty("Foldings", xmlEditor.Document.FoldingManager.SerializeToString());
			return properties;
		}
		
		#endregion
		
		#region IPrintable interface
		
		public PrintDocument PrintDocument{
			get {
				return xmlEditor.PrintDocument;
			}
		}
		
		#endregion
		
		#region ITextEditorControlProvider interface
		
		public TextEditorControl TextEditorControl {
			get {
				return xmlEditor;
			}
		}
		#endregion
	
		#region IPositionable interface

		/// <summary>
		/// Moves the cursor to the specified line and column.
		/// </summary>
		public void JumpTo(int line, int column)
		{
			xmlEditor.ActiveTextAreaControl.JumpTo(line, column);
		}

		#endregion

		protected override void OnFileNameChanged(EventArgs e)
		{
			base.OnFileNameChanged(e);
			xmlEditor.FileName = base.FileName;
		}
		
		static bool IsFileReadOnly(string fileName)
		{
			return (File.GetAttributes(fileName) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly;
		}
		
		/// <summary>
		/// Checks that the file extension refers to an xml file as 
		/// specified in the SyntaxModes.xml file.
		/// </summary>
		static bool IsXmlFileExtension(string extension)
		{
			bool isXmlFileExtension = false;
			
			IHighlightingStrategy strategy = HighlightingManager.Manager.FindHighlighter(XmlView.Language);
			if (strategy != null) {
				foreach (string currentExtension in strategy.Extensions) {
					if (String.Compare(extension, currentExtension, true) == 0) {
						isXmlFileExtension = true;
						break;
					}
				}
			}
			
			return isXmlFileExtension;
		}
		
		/// <summary>
		/// Forces the editor to update its folds.
		/// </summary>
		void UpdateFolding()
		{
			xmlEditor.Document.FoldingManager.UpdateFoldings(String.Empty, null);
			RefreshMargin();
		}
		
		/// <summary>
		/// Repaints the folds in the margin.
		/// </summary>
		void RefreshMargin()
		{
			RefreshDelegate refreshDelegate = new RefreshDelegate(xmlEditor.ActiveTextAreaControl.TextArea.Refresh);
	    	xmlEditor.ActiveTextAreaControl.TextArea.Invoke(refreshDelegate, new object[] { xmlEditor.ActiveTextAreaControl.TextArea.FoldMargin});
		}
		
		/// <summary>
		/// Sets the dirty flag since the document has changed.
		/// </summary>
		void DocumentChanged(object sender, DocumentEventArgs e)
		{
			IsDirty = true;
		}
		
		/// <summary>
		/// Updates the line, col, overwrite/insert mode in the status bar.
		/// </summary>
		void CaretUpdate(object sender, EventArgs e)
		{
			CaretChanged(sender, e);
			CaretModeChanged(sender, e);
		}
		
		/// <summary>
		/// Updates the line, col information in the status bar.
		/// </summary>
		void CaretChanged(object sender, EventArgs e)
		{
			Point pos = xmlEditor.Document.OffsetToPosition(xmlEditor.ActiveTextAreaControl.Caret.Offset);
			LineSegment line = xmlEditor.Document.GetLineSegment(pos.Y);
			IStatusBarService statusBarService = (IStatusBarService)ICSharpCode.Core.Services.ServiceManager.Services.GetService(typeof(IStatusBarService));
			statusBarService.SetCaretPosition(pos.X + 1, pos.Y + 1, xmlEditor.ActiveTextAreaControl.Caret.Offset - line.Offset + 1);
		}
		
		/// <summary>
		/// Updates the insert/overwrite mode text in the status bar.
		/// </summary>
		void CaretModeChanged(object sender, EventArgs e)
		{
			IStatusBarService statusBarService = (IStatusBarService)ICSharpCode.Core.Services.ServiceManager.Services.GetService(typeof(IStatusBarService));
			statusBarService.SetInsertMode(xmlEditor.ActiveTextAreaControl.Caret.CaretMode == CaretMode.InsertMode);
		}
		
		/// <summary>
		/// Creates the file system watcher.
		/// </summary>
		void SetWatcher()
		{
			try {
				if (this.watcher == null) {
					this.watcher = new FileSystemWatcher();
					this.watcher.Changed += new FileSystemEventHandler(this.OnFileChangedEvent);
				} else {
					this.watcher.EnableRaisingEvents = false;
				}
				this.watcher.Path = Path.GetDirectoryName(xmlEditor.FileName);
				this.watcher.Filter = Path.GetFileName(xmlEditor.FileName);
				this.watcher.NotifyFilter = NotifyFilters.LastWrite;
				this.watcher.EnableRaisingEvents = true;
			} catch (Exception) {
				watcher = null;
			}
		}
				
		/// <summary>
		/// Shows the "File was changed" dialog if the file was 
		/// changed externally.
		/// </summary>
		void GotFocusEvent(object sender, EventArgs e)
		{
			lock (this) {
				if (wasChangedExternally) {
					wasChangedExternally = false;
					StringParserService stringParserService = (StringParserService)ServiceManager.Services.GetService(typeof(StringParserService));
					string message = stringParserService.Parse("${res:ICSharpCode.SharpDevelop.DefaultEditor.Gui.Editor.TextEditorDisplayBinding.FileAlteredMessage}", new string[,] {{"File", Path.GetFullPath(xmlEditor.FileName)}});
					if (MessageBox.Show(message,
					                    stringParserService.Parse("${res:MainWindow.DialogName}"),
					                    MessageBoxButtons.YesNo,
					                    MessageBoxIcon.Question) == DialogResult.Yes) {
					                    	Load(xmlEditor.FileName);
					} else {
						IsDirty = true;
					}
				}
			}
		}
		
		void OnFileChangedEvent(object sender, FileSystemEventArgs e)
		{
			lock (this) {
				if(e.ChangeType != WatcherChangeTypes.Deleted) {
					wasChangedExternally = true;
					if (((Form)ICSharpCode.SharpDevelop.Gui.WorkbenchSingleton.Workbench).Focused) {
						GotFocusEvent(this, EventArgs.Empty);
					}
				}
			}
		}
		
		/// <summary>
		/// Gets the xml validation output window.
		/// </summary>
		MessageViewCategory Category {
        	get {
	        	if (category == null) {
					category = new MessageViewCategory("Xml", "Xml");
					CompilerMessageView cmv = (CompilerMessageView)WorkbenchSingleton.Workbench.GetPad(typeof(CompilerMessageView));
					cmv.AddCategory(category);        		
	        	}
	        	
	        	return category;
        	}		
		}
		
		/// <summary>
        /// Writes a line of text to the output window.
        /// </summary>
        /// <param name="message">The message to send to the output
        /// window.</param>
        void OutputWindowWriteLine(string message)
        {
        	Category.AppendText(String.Concat(message, Environment.NewLine));
        }
        
        void ClearTasks()
        {
        	if (HasTasks) {
        		TaskService taskService = (TaskService)ICSharpCode.Core.Services.ServiceManager.Services.GetService(typeof(TaskService));
        		taskService.Tasks.Clear();
        		taskService.NotifyTaskChange();
        	}
        }
        
        bool ShowTaskListAfterBuild {
        	get {
        		PropertyService propertyService = (PropertyService)ICSharpCode.Core.Services.ServiceManager.Services.GetService(typeof(PropertyService));
        		return ((bool)propertyService.GetProperty("SharpDevelop.ShowTaskListAfterBuild", true));
        	}
        }
        
        bool HasTasks {
        	get {
        		bool hasTasks = false;
        		TaskService taskService = (TaskService)ICSharpCode.Core.Services.ServiceManager.Services.GetService(typeof(TaskService));
        		if (taskService.Tasks.Count > 0) {
        			hasTasks = true;
        		}
        		return hasTasks;
        	}
        }
        
        void ShowTasks()
        {
        	IWorkbench workBench = (IWorkbench)ICSharpCode.SharpDevelop.Gui.WorkbenchSingleton.Workbench;
			IPadContent PadContent = workBench.GetPad(typeof(OpenTaskView));
					
			if (PadContent != null) {
				PadContent.BringPadToFront();
			}	
        }     
        
        void AddTask(string fileName, string message, int column, int line, TaskType taskType)
        {
			Task task = new Task(fileName, message, column, line, taskType);	                     
       		TaskService taskService = (TaskService)ICSharpCode.Core.Services.ServiceManager.Services.GetService(typeof(TaskService));
 			taskService.Tasks.Add(task);
			taskService.NotifyTaskChange();
        }
        
        /// <summary>
        /// Displays the validation error.
        /// </summary>
        void DisplayValidationError(string fileName, string message, int column, int line)
        {
        	OutputWindowWriteLine(message);
			OutputWindowWriteLine(String.Empty);
			OutputWindowWriteLine(stringParserService.Parse("${res:MainWindow.XmlValidationMessages.ValidationFailed}"));
			AddTask(fileName, message, column, line, TaskType.Error);
        }
        
        /// <summary>
        /// Updates the default schema associated with the xml editor.
        /// </summary>
        void PropertyChanged(object sender, PropertyEventArgs args)
        {
        	string extension = Path.GetExtension(xmlEditor.FileName).ToLower();
        	if (args.Key.ToLower() == extension) {
        		SetDefaultSchema(extension);
        	} else if (args.Key == XmlEditorAddInOptions.ShowAttributesWhenFoldedPropertyName) {
        		UpdateFolding();
        		xmlEditor.Refresh();
        	}
        }

        /// <summary>
        /// Sets the default schema and namespace prefix that the xml editor will use.
        /// </summary>
        void SetDefaultSchema(string extension)
        {
 	        xmlEditor.DefaultSchemaCompletionData = XmlSchemaManager.GetSchemaCompletionData(extension);
 	        xmlEditor.DefaultNamespacePrefix = XmlSchemaManager.GetNamespacePrefix(extension);
        }
        
        /// <summary>
        /// Updates the default schema association since the schema
        /// may have been added.
        /// </summary>
        void UserSchemaAdded(object source, EventArgs e)
        {
        	SetDefaultSchema(Path.GetExtension(xmlEditor.FileName).ToLower());
        }
        
        /// <summary>
        /// Updates the default schema association since the schema
        /// may have been removed.
        /// </summary>
        void UserSchemaRemoved(object source, EventArgs e)
        {
        	SetDefaultSchema(Path.GetExtension(xmlEditor.FileName).ToLower());
        }       
	}
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -