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

📄 xmlview.cs

📁 SharpDevelop2.0.0 c#开发免费工具
💻 CS
📖 第 1 页 / 共 2 页
字号:
// <file>
//     <copyright see="prj:///doc/copyright.txt"/>
//     <license see="prj:///doc/license.txt"/>
//     <owner name="Matthew Ward" email="mrward@users.sourceforge.net"/>
//     <version>$Revision: 1046 $</version>
// </file>

using ICSharpCode.Core;
using ICSharpCode.SharpDevelop;
using ICSharpCode.SharpDevelop.DefaultEditor.Gui.Editor;
using ICSharpCode.SharpDevelop.Gui;
using ICSharpCode.TextEditor;
using ICSharpCode.TextEditor.Document;
using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using System.Xml.Schema;
using System.Xml.XPath;
using System.Xml.Xsl;

namespace ICSharpCode.XmlEditor
{
	/// <summary>
	/// Wrapper class for the XmlEditor used when displaying the xml file.
	/// </summary>
	public class XmlView : AbstractViewContent, IEditable, IClipboardHandler, IParseInformationListener, IMementoCapable, IPrintable, ITextEditorControlProvider, IPositionable
	{
		/// <summary>
		/// The language handled by this view.
		/// </summary>
		public static readonly string Language = "XML";
		
		/// <summary>
		/// Output window category name.
		/// </summary>
		public static readonly string CategoryName = "XML";

		delegate void RefreshDelegate(AbstractMargin margin);

		XmlEditorControl xmlEditor = new XmlEditorControl();
		FileSystemWatcher watcher;
		bool wasChangedExternally;
		static MessageViewCategory category;
		string stylesheetFileName;
		
		public XmlView()
		{
			xmlEditor.Dock = DockStyle.Fill;
			
			xmlEditor.SchemaCompletionDataItems = XmlSchemaManager.SchemaCompletionDataItems;
			xmlEditor.Document.DocumentChanged += new DocumentEventHandler(DocumentChanged);
			
			xmlEditor.ActiveTextAreaControl.Caret.CaretModeChanged += new EventHandler(CaretModeChanged);
			xmlEditor.ActiveTextAreaControl.Enter += new EventHandler(CaretUpdate);
			((Form)ICSharpCode.SharpDevelop.Gui.WorkbenchSingleton.Workbench).Activated += new EventHandler(GotFocusEvent);
			
			// Listen for changes to the xml editor properties.
			XmlEditorAddInOptions.PropertyChanged += PropertyChanged;
			XmlSchemaManager.UserSchemaAdded += new EventHandler(UserSchemaAdded);
			XmlSchemaManager.UserSchemaRemoved += new EventHandler(UserSchemaRemoved);
		}

		public override string TabPageText {
			get {
				return "XML";
			}
		}
		
		/// <summary>
		/// Loads the string content into the view.
		/// </summary>
		public void LoadContent(string content)
		{
			xmlEditor.Document.TextContent = StringParser.Parse(content);
			xmlEditor.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy(XmlView.Language);
			UpdateFolding();
		}
		
		/// <summary>
		/// Can create content for the 'XML' language.
		/// </summary>
		public static bool IsLanguageHandled(string language)
		{
			return language == XmlView.Language;
		}
		
		/// <summary>
		/// Returns whether the view can handle the specified file.
		/// </summary>
		public static bool IsFileNameHandled(string fileName)
		{
			return IsXmlFileExtension(Path.GetExtension(fileName));
		}
		
		/// <summary>
		/// Gets the known xml file extensions.
		/// </summary>
		public static string[] GetXmlFileExtensions()
		{
			IHighlightingStrategy strategy = HighlightingManager.Manager.FindHighlighter(XmlView.Language);
			if (strategy != null) {
				return strategy.Extensions;
			}
			
			return new string[0];
		}
		
		/// <summary>
		/// Validates the xml against known schemas.
		/// </summary>
		public void ValidateXml()
		{
			TaskService.ClearExceptCommentTasks();
			Category.ClearText();
			ShowOutputWindow();
			
			OutputWindowWriteLine(StringParser.Parse("${res:MainWindow.XmlValidationMessages.ValidationStarted}"));

			try {
				StringReader stringReader = new StringReader(xmlEditor.Document.TextContent);
				XmlTextReader xmlReader = new XmlTextReader(stringReader);
				xmlReader.XmlResolver = null;
				XmlReaderSettings settings = new XmlReaderSettings();
				settings.ValidationType = ValidationType.Schema;
				settings.ValidationFlags = XmlSchemaValidationFlags.None;
				settings.XmlResolver = null;
				
				XmlSchemaCompletionData schemaData = null;
				try {
					for (int i = 0; i < XmlSchemaManager.SchemaCompletionDataItems.Count; ++i) {
						schemaData = XmlSchemaManager.SchemaCompletionDataItems[i];
						settings.Schemas.Add(schemaData.Schema);
					}
				} catch (XmlSchemaException ex) {
					DisplayValidationError(schemaData.FileName, ex.Message, ex.LinePosition - 1, ex.LineNumber - 1);
					ShowErrorList();
					return;
				}
				
				XmlReader reader = XmlReader.Create(xmlReader, settings);
				
				XmlDocument doc = new XmlDocument();
				doc.Load(reader);
				
				OutputWindowWriteLine(String.Empty);
				OutputWindowWriteLine(StringParser.Parse("${res:MainWindow.XmlValidationMessages.ValidationSuccess}"));
				
			} catch (XmlSchemaException ex) {
				DisplayValidationError(xmlEditor.FileName, ex.Message, ex.LinePosition - 1, ex.LineNumber - 1);
			} catch (XmlException ex) {
				DisplayValidationError(xmlEditor.FileName, ex.Message, ex.LinePosition - 1, ex.LineNumber - 1);
			}
			
			ShowErrorList();
		}
		
		/// <summary>
		/// Gets the name of a new view.
		/// </summary>
		public override string UntitledName {
			get {
				return base.UntitledName;
			}
			set {
				base.UntitledName = value;
				xmlEditor.FileName = value;
				SetDefaultSchema(Path.GetExtension(xmlEditor.FileName));
			}
		}
		
		public override void Dispose()
		{
			base.Dispose();
			((Form)ICSharpCode.SharpDevelop.Gui.WorkbenchSingleton.Workbench).Activated -= new EventHandler(GotFocusEvent);
			
			XmlEditorAddInOptions.PropertyChanged -= PropertyChanged;
			XmlSchemaManager.UserSchemaAdded -= new EventHandler(UserSchemaAdded);
			XmlSchemaManager.UserSchemaRemoved -= new EventHandler(UserSchemaRemoved);
			
			xmlEditor.Dispose();
		}
		
		/// <summary>
		/// Sets the filename associated with the view.
		/// </summary>
		public override string FileName {
			set {
				if (Path.GetExtension(FileName) != Path.GetExtension(value)) {
					if (xmlEditor.Document.HighlightingStrategy != null) {
						xmlEditor.Document.HighlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategyForFile(value);
						xmlEditor.Refresh();
					}
				}
				base.FileName  = value;
				base.TitleName = Path.GetFileName(value);
				
				SetDefaultSchema(Path.GetExtension(value));
			}
		}
		
		/// <summary>
		/// Gets or sets the stylesheet associated with this xml file.
		/// </summary>
		public string StylesheetFileName {
			get {
				return stylesheetFileName;
			}
			
			set {
				stylesheetFileName = value;
			}
		}
		
		/// <summary>
		/// Applys the stylesheet to the xml and displays the resulting output.
		/// </summary>
		public void RunXslTransform(string xsl)
		{
			try {
				WorkbenchSingleton.Workbench.GetPad(typeof(CompilerMessageView)).BringPadToFront();
				
				TaskService.ClearExceptCommentTasks();
				
				if (IsWellFormed) {
					if (IsValidXsl(xsl)) {
						string transformedXml = Transform(Text, xsl);
						ShowTransformOutput(transformedXml);
					}
				}
				
				ShowErrorList();
				
			} catch (Exception ex) {
				MessageService.ShowError(ex);
			}
		}
		
		#region IEditable interface
		
		public IClipboardHandler ClipboardHandler {
			get {
				return this;
			}
		}
		
		public bool EnableUndo {
			get {
				return xmlEditor.EnableUndo;
			}
		}
		
		public bool EnableRedo {
			get {
				return xmlEditor.EnableUndo;
			}
		}
		
		// ParserUpdateThread uses the text property via IEditable, I had an exception
		// because multiple threads were accessing the GapBufferStrategy at the same time.
		
		string GetText()
		{
			return xmlEditor.Document.TextContent;
		}
		
		void SetText(string value)
		{
			xmlEditor.Document.TextContent = value;
		}
		
		public string Text {
			get {
				if (WorkbenchSingleton.InvokeRequired)
					return (string)WorkbenchSingleton.SafeThreadCall(this, "GetText", null);
				else
					return GetText();
			}
			set {
				if (WorkbenchSingleton.InvokeRequired)
					WorkbenchSingleton.SafeThreadCall(this, "SetText", value);
				else
					SetText(value);
			}
		}
		
		public void Redo()
		{
			xmlEditor.Redo();
		}
		
		public void Undo()
		{
			xmlEditor.Undo();
		}
		
		#endregion
		
		#region AbstractViewContent implementation
		
		public override Control Control {
			get {
				return xmlEditor;
			}
		}
		
		public override void Load(string fileName)
		{
			xmlEditor.IsReadOnly = IsFileReadOnly(fileName);
			xmlEditor.LoadFile(fileName);
			FileName  = fileName;
			TitleName = Path.GetFileName(fileName);
			IsDirty     = false;
			UpdateFolding();
			SetWatcher();
		}
		
		public override void Save(string fileName)
		{
			OnSaving(EventArgs.Empty);

			if (watcher != null) {
				watcher.EnableRaisingEvents = false;
			}

			xmlEditor.SaveFile(fileName);
			FileName = fileName;
			TitleName = Path.GetFileName(fileName);
			IsDirty = false;
			
			SetWatcher();
			OnSaved(new SaveEventArgs(true));
		}
		
		
		#endregion
		
		#region IClipboardHandler interface

		public bool EnableCut {
			get {
				return xmlEditor.ActiveTextAreaControl.TextArea.ClipboardHandler.EnableCut;
			}
		}
		
		public bool EnableCopy {
			get {
				return xmlEditor.ActiveTextAreaControl.TextArea.ClipboardHandler.EnableCopy;
			}
		}
		
		public bool EnablePaste {
			get {
				return xmlEditor.ActiveTextAreaControl.TextArea.ClipboardHandler.EnablePaste;
			}
		}
		
		public bool EnableDelete {
			get {
				return xmlEditor.ActiveTextAreaControl.TextArea.ClipboardHandler.EnableDelete;
			}
		}
		
		public bool EnableSelectAll {
			get {
				return xmlEditor.ActiveTextAreaControl.TextArea.ClipboardHandler.EnableSelectAll;
			}
		}
		
		public void SelectAll()
		{
			xmlEditor.ActiveTextAreaControl.TextArea.ClipboardHandler.SelectAll(null, EventArgs.Empty);
		}
		
		public void Delete()
		{
			xmlEditor.ActiveTextAreaControl.TextArea.ClipboardHandler.Delete(null, EventArgs.Empty);
		}
		
		public void Paste()
		{
			xmlEditor.ActiveTextAreaControl.TextArea.ClipboardHandler.Paste(null, EventArgs.Empty);
		}
		
		public void Copy()
		{
			xmlEditor.ActiveTextAreaControl.TextArea.ClipboardHandler.Copy(null, EventArgs.Empty);
		}
		
		public void Cut()
		{
			xmlEditor.ActiveTextAreaControl.TextArea.ClipboardHandler.Cut(null, EventArgs.Empty);
		}
		
		#endregion
		
		#region IParseInformationListener interface
		
		public void ParseInformationUpdated(ParseInformation parseInfo)
		{
			WorkbenchSingleton.SafeThreadAsyncCall((MethodInvoker)UpdateFolding);
		}
		
		#endregion
		
		#region IMementoCapable interface
		
		public void SetMemento(Properties properties)
		{
			xmlEditor.ActiveTextAreaControl.Caret.Position =  xmlEditor.Document.OffsetToPosition(Math.Min(xmlEditor.Document.TextLength, Math.Max(0, properties.Get("CaretOffset", xmlEditor.ActiveTextAreaControl.Caret.Offset))));

			if (xmlEditor.Document.HighlightingStrategy.Name != properties.Get("HighlightingLanguage", xmlEditor.Document.HighlightingStrategy.Name)) {
				IHighlightingStrategy highlightingStrategy = HighlightingStrategyFactory.CreateHighlightingStrategy(properties.Get("HighlightingLanguage", xmlEditor.Document.HighlightingStrategy.Name));
				if (highlightingStrategy != null) {
					xmlEditor.Document.HighlightingStrategy = highlightingStrategy;
				}
			}
			xmlEditor.ActiveTextAreaControl.TextArea.TextView.FirstVisibleLine = properties.Get("VisibleLine", 0);
			
			xmlEditor.Document.FoldingManager.DeserializeFromString(properties.Get("Foldings", ""));
		}
		
		public Properties CreateMemento()
		{
			Properties properties = new Properties();
			properties.Set("CaretOffset", xmlEditor.ActiveTextAreaControl.Caret.Offset);
			properties.Set("VisibleLine", xmlEditor.ActiveTextAreaControl.TextArea.TextView.FirstVisibleLine);
			properties.Set("HighlightingLanguage", xmlEditor.Document.HighlightingStrategy.Name);
			properties.Set("Foldings", xmlEditor.Document.FoldingManager.SerializeToString());
			return properties;
		}
		
		#endregion
		

⌨️ 快捷键说明

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