aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/Scripting/Tango.Scripting.Editors/Search/SearchPanel.cs
blob: b4af99f5407b58a7cba9c871c19e9ea8cc4a0435 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
pre { line-height: 125%; }
td.linenos .normal { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
span.linenos { color: inherit; background-color: transparent; padding-left: 5px; padding-right: 5px; }
td.linenos .special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
span.linenos.special { color: #000000; background-color: #ffffc0; padding-left: 5px; padding-right: 5px; }
.highlight .hll { background-color: #ffffcc }
.highlight .c { color: #888888 } /* Comment */
.highlight .err { color: #a61717; background-color: #e3d2d2 } /* Error */
.highlight .k { color: #008800; font-weight: bold } /* Keyword */
.highlight .ch { color: #888888 } /* Comment.Hashbang */
.highlight .cm { color: #888888 } /* Comment.Multiline */
.highlight .cp { color: #cc0000; font-weight: bold } /* Comment.Preproc */
.highlight .cpf { color: #888888 } /* Comment.PreprocFile */
.highlight .c1 { color: #888888 } /* Comment.Single */
.highlight .cs { color: #cc0000; font-weight: bold; background-color: #fff0f0 } /* Comment.Special */
.highlight .gd { color: #000000; background-color: #ffdddd } /* Generic.Deleted */
.highlight .ge { font-style: italic } /* Generic.Emph */
.highlight .ges { font-weight: bold; font-style: italic } /* Generic.EmphStrong */
.highlight .gr { color: #aa0000 } /* Generic.Error */
.highlight .gh { color: #333333 } /* Generic.Heading */
.highlight .gi { color: #000000; background-color: #ddffdd } /* Generic.Inserted */
.highlight .go { color: #888888 } /* Generic.Output */
.highlight .gp { color: #555555 } /* Generic.Prompt */
.highlight .gs { font-weight: bold } /* Generic.Strong */
.highlight .gu { color: #666666 } /* Generic.Subheading */
.highlight .gt { color: #aa0000 } /* Generic.Traceback */
.highlight .kc { color: #008800; font-weight: bold } /* Keyword.Constant */
.highlight .kd { color: #008800; font-weight: bold } /* Keyword.Declaration */
.highlight .kn { color: #008800; font-weight: bold } /* Keyword.Namespace */
.highlight .kp { color: #008800 } /* Keyword.Pseudo */
.highlight .kr { color: #008800; font-weight: bold } /* Keyword.Reserved */
.highlight .kt { color: #888888; font-weight: bold } /* Keyword.Type */
.highlight .m { color: #0000DD; font-weight: bold } /* Literal.Number */
.highlight .s { color: #dd2200; background-color: #fff0f0 } /* Literal.String */
.highlight .na { color: #336699 } /* Name.Attribute */
.highlight .nb { color: #003388 } /* Name.Builtin */
.highlight .nc { color: #bb0066; font-weight: bold } /* Name.Class */
.highlight .no { color: #003366; font-weight: bold } /* Name.Constant */
.highlight .nd { color: #555555 } /* Name.Decorator */
.highlight .ne { color: #bb0066; font-weight: bold } /* Name.Exception */
.highlight .nf { color: #0066bb; font-weight: bold } /* Name.Function */
.highlight .nl { color: #336699; font-style: italic } /* Name.Label */
.highlight .nn { color: #bb0066; font-weight: bold } /* Name.Namespace */
.highlight .py { color: #336699; font-weight: bold } /* Name.Property */
.highlight .nt { color: #bb0066; font-weight: bold } /* Name.Tag */
.highlight .nv { color: #336699 } /* Name.Variable */
.highlight .ow { color: #008800 } /* Operator.Word */
.highlight .w { color: #bbbbbb } /* Text.Whitespace */
.highlight .mb { color: #0000DD; font-weight: bold } /* Literal.Number.Bin */
.highlight .mf { color: #0000DD; font-weight: bold } /* Literal.Number.Float */
.highlight .mh { color: #0000DD; font-weight: bold } /* Literal.Number.Hex */
.highlight .mi { color: #0000DD; font-weight: bold } /* Literal.Number.Integer */
.highlight .mo { color: #0000DD; font-weight: bold } /* Literal.Number.Oct */
.highlight .sa { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Affix */
.highlight .sb { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Backtick */
.highlight .sc { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Char */
.highlight .dl { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Delimiter */
.highlight .sd { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Doc */
.highlight .s2 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Double */
.highlight .se { color: #0044dd; background-color: #fff0f0 } /* Literal.String.Escape */
.highlight .sh { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Heredoc */
.highlight .si { color: #3333bb; background-color: #fff0f0 } /* Literal.String.Interpol */
.highlight .sx { color: #22bb22; background-color: #f0fff0 } /* Literal.String.Other */
.highlight .sr { color: #008800; background-color: #fff0ff } /* Literal.String.Regex */
.highlight .s1 { color: #dd2200; background-color: #fff0f0 } /* Literal.String.Single */
.highlight .ss { color: #aa6600; background-color: #fff0f0 } /* Literal.String.Symbol */
.highlight .bp { color: #003388 } /* Name.Builtin.Pseudo */
.highlight .fm { color: #0066bb; font-weight: bold } /* Name.Function.Magic */
.highlight .vc { color: #336699 } /* Name.Variable.Class */
.highlight .vg { color: #dd7700 } /* Name.Variable.Global */
.highlight .vi { color: #3333bb } /* Name.Variable.Instance */
.highlight .vm { color: #336699 } /* Name.Variable.Magic */
.highlight .il { color: #0000DD; font-weight: bold } /* Literal.Number.Integer.Long */
/* Generated by the protocol buffer compiler.  DO NOT EDIT! */
/* Generated from: ContinueThreadLoadingRequest.proto */

#ifndef PROTOBUF_C_ContinueThreadLoadingRequest_2eproto__INCLUDED
#define PROTOBUF_C_ContinueThreadLoadingRequest_2eproto__INCLUDED

#include <protobuf-c/protobuf-c.h>

PROTOBUF_C__BEGIN_DECLS

#if PROTOBUF_C_VERSION_NUMBER < 1003000
# error This file was generated by a newer version of protoc-c which is incompatible with your libprotobuf-c headers. Please update your headers.
#elif 1003000 < PROTOBUF_C_MIN_COMPILER_VERSION
# error This file was generated by an older version of protoc-c which is incompatible with your libprotobuf-c headers. Please regenerate this file with a newer version of protoc-c.
#endif

#include "ProcessParameters.pb-c.h"

typedef struct _ContinueThreadLoadingRequest ContinueThreadLoadingRequest;


/* --- enums --- */


/* --- messages --- */

struct  _ContinueThreadLoadingRequest
{
  ProtobufCMessage base;
  ProcessParameters *processparameters;
};
#define CONTINUE_THREAD_LOADING_REQUEST__INIT \
 { PROTOBUF_C_MESSAGE_INIT (&continue_thread_loading_request__descriptor) \
    , NULL }


/* ContinueThreadLoadingRequest methods */
void   continue_thread_loading_request__init
                     (ContinueThreadLoadingRequest         *message);
size_t continue_thread_loading_request__get_packed_size
                     (const ContinueThreadLoadingRequest   *message);
size_t continue_thread_loading_request__pack
                     (const ContinueThreadLoadingRequest   *message,
                      uint8_t             *out);
size_t continue_thread_loading_request__pack_to_buffer
                     (const ContinueThreadLoadingRequest   *message,
                      ProtobufCBuffer     *buffer);
ContinueThreadLoadingRequest *
       continue_thread_loading_request__unpack
                     (ProtobufCAllocator  *allocator,
                      size_t               len,
                      const uint8_t       *data);
void   continue_thread_loading_request__free_unpacked
                     (ContinueThreadLoadingRequest *message,
                      ProtobufCAllocator *allocator);
/* --- per-message closures --- */

typedef void (*ContinueThreadLoadingRequest_Closure)
                 (const ContinueThreadLoadingRequest *message,
                  void *closure_data);

/* --- services --- */


/* --- descriptors --- */

extern const ProtobufCMessageDescriptor continue_thread_loading_request__descriptor;

PROTOBUF_C__END_DECLS


#endif  /* PROTOBUF_C_ContinueThreadLoadingRequest_2eproto__INCLUDED */
f='#n454'>454 455 456 457 458 459 460 461 462 463 464 465 466 467
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt)
// This code is distributed under the GNU LGPL (for details please see \doc\license.txt)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Controls.Primitives;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Threading;
using Tango.Scripting.Editors.Document;
using Tango.Scripting.Editors.Editing;
using Tango.Scripting.Editors.Folding;
using Tango.Scripting.Editors.Rendering;

namespace Tango.Scripting.Editors.Search
{
	/// <summary>
	/// Provides search functionality for AvalonEdit. It is displayed in the top-right corner of the TextArea.
	/// </summary>
	public class SearchPanel : Control
	{
		TextArea textArea;
		TextDocument currentDocument;
		SearchResultBackgroundRenderer renderer;
		TextBox searchTextBox;
		SearchPanelAdorner adorner;
		
		#region DependencyProperties
		/// <summary>
		/// Dependency property for <see cref="UseRegex"/>.
		/// </summary>
		public static readonly DependencyProperty UseRegexProperty =
			DependencyProperty.Register("UseRegex", typeof(bool), typeof(SearchPanel),
			                            new FrameworkPropertyMetadata(false, SearchPatternChangedCallback));
		
		/// <summary>
		/// Gets/sets whether the search pattern should be interpreted as regular expression.
		/// </summary>
		public bool UseRegex {
			get { return (bool)GetValue(UseRegexProperty); }
			set { SetValue(UseRegexProperty, value); }
		}
		
		/// <summary>
		/// Dependency property for <see cref="MatchCase"/>.
		/// </summary>
		public static readonly DependencyProperty MatchCaseProperty =
			DependencyProperty.Register("MatchCase", typeof(bool), typeof(SearchPanel),
			                            new FrameworkPropertyMetadata(false, SearchPatternChangedCallback));
		
		/// <summary>
		/// Gets/sets whether the search pattern should be interpreted case-sensitive.
		/// </summary>
		public bool MatchCase {
			get { return (bool)GetValue(MatchCaseProperty); }
			set { SetValue(MatchCaseProperty, value); }
		}
		
		/// <summary>
		/// Dependency property for <see cref="WholeWords"/>.
		/// </summary>
		public static readonly DependencyProperty WholeWordsProperty =
			DependencyProperty.Register("WholeWords", typeof(bool), typeof(SearchPanel),
			                            new FrameworkPropertyMetadata(false, SearchPatternChangedCallback));
		
		/// <summary>
		/// Gets/sets whether the search pattern should only match whole words.
		/// </summary>
		public bool WholeWords {
			get { return (bool)GetValue(WholeWordsProperty); }
			set { SetValue(WholeWordsProperty, value); }
		}
		
		/// <summary>
		/// Dependency property for <see cref="SearchPattern"/>.
		/// </summary>
		public static readonly DependencyProperty SearchPatternProperty =
			DependencyProperty.Register("SearchPattern", typeof(string), typeof(SearchPanel),
			                            new FrameworkPropertyMetadata("", SearchPatternChangedCallback));
		
		/// <summary>
		/// Gets/sets the search pattern.
		/// </summary>
		public string SearchPattern {
			get { return (string)GetValue(SearchPatternProperty); }
			set { SetValue(SearchPatternProperty, value); }
		}
		
		/// <summary>
		/// Dependency property for <see cref="MarkerBrush"/>.
		/// </summary>
		public static readonly DependencyProperty MarkerBrushProperty =
			DependencyProperty.Register("MarkerBrush", typeof(Brush), typeof(SearchPanel),
			                            new FrameworkPropertyMetadata(Brushes.LightGreen, MarkerBrushChangedCallback));
		
		/// <summary>
		/// Gets/sets the Brush used for marking search results in the TextView.
		/// </summary>
		public Brush MarkerBrush {
			get { return (Brush)GetValue(MarkerBrushProperty); }
			set { SetValue(MarkerBrushProperty, value); }
		}
		
		/// <summary>
		/// Dependency property for <see cref="Localization"/>.
		/// </summary>
		public static readonly DependencyProperty LocalizationProperty =
			DependencyProperty.Register("Localization", typeof(Localization), typeof(SearchPanel),
			                            new FrameworkPropertyMetadata(new Localization()));
		
		/// <summary>
		/// Gets/sets the localization for the SearchPanel.
		/// </summary>
		public Localization Localization {
			get { return (Localization)GetValue(LocalizationProperty); }
			set { SetValue(LocalizationProperty, value); }
		}
		#endregion
		
		static void MarkerBrushChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			SearchPanel panel = d as SearchPanel;
			if (panel != null) {
				panel.renderer.MarkerBrush = (Brush)e.NewValue;
			}
		}
		
		static SearchPanel()
		{
			DefaultStyleKeyProperty.OverrideMetadata(typeof(SearchPanel), new FrameworkPropertyMetadata(typeof(SearchPanel)));
		}
		
		ISearchStrategy strategy;
		
		static void SearchPatternChangedCallback(DependencyObject d, DependencyPropertyChangedEventArgs e)
		{
			SearchPanel panel = d as SearchPanel;
			if (panel != null) {
				panel.ValidateSearchText();
				panel.UpdateSearch();
			}
		}

		void UpdateSearch()
		{
			// only reset as long as there are results
			// if no results are found, the "no matches found" message should not flicker.
			// if results are found by the next run, the message will be hidden inside DoSearch ...
			if (renderer.CurrentResults.Any())
				messageView.IsOpen = false;
			strategy = SearchStrategyFactory.Create(SearchPattern ?? "", !MatchCase, WholeWords, UseRegex ? SearchMode.RegEx : SearchMode.Normal);
			OnSearchOptionsChanged(new SearchOptionsChangedEventArgs(SearchPattern, MatchCase, UseRegex, WholeWords));
			DoSearch(true);
		}
		
		/// <summary>
		/// Creates a new SearchPanel.
		/// </summary>
		public SearchPanel()
		{
		}
		
		/// <summary>
		/// Attaches this SearchPanel to a TextArea instance.
		/// </summary>
		public void Attach(TextArea textArea)
		{
			if (textArea == null)
				throw new ArgumentNullException("textArea");
			this.textArea = textArea;
			adorner = new SearchPanelAdorner(textArea, this);
			DataContext = this;
			
			renderer = new SearchResultBackgroundRenderer();
			currentDocument = textArea.Document;
			if (currentDocument != null)
				currentDocument.TextChanged += textArea_Document_TextChanged;
			textArea.DocumentChanged += textArea_DocumentChanged;
			KeyDown += SearchLayerKeyDown;
			
			this.CommandBindings.Add(new CommandBinding(SearchCommands.FindNext, (sender, e) => FindNext()));
			this.CommandBindings.Add(new CommandBinding(SearchCommands.FindPrevious, (sender, e) => FindPrevious()));
			this.CommandBindings.Add(new CommandBinding(SearchCommands.CloseSearchPanel, (sender, e) => Close()));
			IsClosed = true;
		}

		void textArea_DocumentChanged(object sender, EventArgs e)
		{
			if (currentDocument != null)
				currentDocument.TextChanged -= textArea_Document_TextChanged;
			currentDocument = textArea.Document;
			if (currentDocument != null) {
				currentDocument.TextChanged += textArea_Document_TextChanged;
				DoSearch(false);
			}
		}

		void textArea_Document_TextChanged(object sender, EventArgs e)
		{
			DoSearch(false);
		}
		
		/// <inheritdoc/>
		public override void OnApplyTemplate()
		{
			base.OnApplyTemplate();
			searchTextBox = Template.FindName("PART_searchTextBox", this) as TextBox;
		}
		
		void ValidateSearchText()
		{
			if (searchTextBox == null)
				return;
			var be = searchTextBox.GetBindingExpression(TextBox.TextProperty);
			try {
				Validation.ClearInvalid(be);
				UpdateSearch();
			} catch (SearchPatternException ex) {
				var ve = new ValidationError(be.ParentBinding.ValidationRules[0], be, ex.Message, ex);
				Validation.MarkInvalid(be, ve);
			}
		}
		
		/// <summary>
		/// Reactivates the SearchPanel by setting the focus on the search box and selecting all text.
		/// </summary>
		public void Reactivate()
		{
			if (searchTextBox == null)
				return;
			searchTextBox.Focus();
			searchTextBox.SelectAll();
		}
		
		/// <summary>
		/// Moves to the next occurrence in the file.
		/// </summary>
		public void FindNext()
		{
			SearchResult result = renderer.CurrentResults.FindFirstSegmentWithStartAfter(textArea.Caret.Offset + 1);
			if (result == null)
				result = renderer.CurrentResults.FirstSegment;
			if (result != null) {
				SelectResult(result);
			}
		}

		/// <summary>
		/// Moves to the previous occurrence in the file.
		/// </summary>
		public void FindPrevious()
		{
			SearchResult result = renderer.CurrentResults.FindFirstSegmentWithStartAfter(textArea.Caret.Offset);
			if (result != null)
				result = renderer.CurrentResults.GetPreviousSegment(result);
			if (result == null)
				result = renderer.CurrentResults.LastSegment;
			if (result != null) {
				SelectResult(result);
			}
		}
		
		ToolTip messageView = new ToolTip { Placement = PlacementMode.Bottom, StaysOpen = false };

		void DoSearch(bool changeSelection)
		{
			if (IsClosed)
				return;
			renderer.CurrentResults.Clear();
			
			if (!string.IsNullOrEmpty(SearchPattern)) {
				int offset = textArea.Caret.Offset;
				if (changeSelection) {
					textArea.ClearSelection();
				}
				// We cast from ISearchResult to SearchResult; this is safe because we always use the built-in strategy
				foreach (SearchResult result in strategy.FindAll(textArea.Document, 0, textArea.Document.TextLength)) {
					if (changeSelection && result.StartOffset >= offset) {
						SelectResult(result);
						changeSelection = false;
					}
					renderer.CurrentResults.Add(result);
				}
				if (!renderer.CurrentResults.Any()) {
					messageView.IsOpen = true;
					messageView.Content = Localization.NoMatchesFoundText;
					messageView.PlacementTarget = searchTextBox;
				} else
					messageView.IsOpen = false;
			}
			textArea.TextView.InvalidateLayer(KnownLayer.Selection);
		}

		void SelectResult(SearchResult result)
		{
			textArea.Caret.Offset = result.StartOffset;
			textArea.Selection = Selection.Create(textArea, result.StartOffset, result.EndOffset);
			textArea.Caret.BringCaretToView();
			// show caret even if the editor does not have the Keyboard Focus
			textArea.Caret.Show();
		}
		
		void SearchLayerKeyDown(object sender, KeyEventArgs e)
		{
			switch (e.Key) {
				case Key.Enter:
					e.Handled = true;
					messageView.IsOpen = false;
					if ((Keyboard.Modifiers & ModifierKeys.Shift) == ModifierKeys.Shift)
						FindPrevious();
					else
						FindNext();
					if (searchTextBox != null) {
						var error = Validation.GetErrors(searchTextBox).FirstOrDefault();
						if (error != null) {
							messageView.Content = Localization.ErrorText + " " + error.ErrorContent;
							messageView.PlacementTarget = searchTextBox;
							messageView.IsOpen = true;
						}
					}
					break;
				case Key.Escape:
					e.Handled = true;
					Close();
					break;
			}
		}
		
		/// <summary>
		/// Gets whether the Panel is already closed.
		/// </summary>
		public bool IsClosed { get; private set; }
		
		/// <summary>
		/// Closes the SearchPanel.
		/// </summary>
		public void Close()
		{
			bool hasFocus = this.IsKeyboardFocusWithin;
			
			var layer = AdornerLayer.GetAdornerLayer(textArea);
			if (layer != null)
				layer.Remove(adorner);
			messageView.IsOpen = false;
			textArea.TextView.BackgroundRenderers.Remove(renderer);
			if (hasFocus)
				textArea.Focus();
			IsClosed = true;
			
			// Clear existing search results so that the segments don't have to be maintained
			renderer.CurrentResults.Clear();
		}
		
		/// <summary>
		/// Closes the SearchPanel and removes it.
		/// </summary>
		public void CloseAndRemove()
		{
			Close();
			textArea.DocumentChanged -= textArea_DocumentChanged;
			if (currentDocument != null)
				currentDocument.TextChanged -= textArea_Document_TextChanged;
		}
		
		/// <summary>
		/// Opens the an existing search panel.
		/// </summary>
		public void Open()
		{
			if (!IsClosed) return;
			var layer = AdornerLayer.GetAdornerLayer(textArea);
			if (layer != null)
				layer.Add(adorner);
			textArea.TextView.BackgroundRenderers.Add(renderer);
			IsClosed = false;
			DoSearch(false);
		}
		
		/// <summary>
		/// Fired when SearchOptions are changed inside the SearchPanel.
		/// </summary>
		public event EventHandler<SearchOptionsChangedEventArgs> SearchOptionsChanged;
		
		/// <summary>
		/// Raises the <see cref="SearchPanel.SearchOptionsChanged" /> event.
		/// </summary>
		protected virtual void OnSearchOptionsChanged(SearchOptionsChangedEventArgs e)
		{
			if (SearchOptionsChanged != null) {
				SearchOptionsChanged(this, e);
			}
		}
	}
	
	/// <summary>
	/// EventArgs for <see cref="SearchPanel.SearchOptionsChanged"/> event.
	/// </summary>
	public class SearchOptionsChangedEventArgs : EventArgs
	{
		/// <summary>
		/// Gets the search pattern.
		/// </summary>
		public string SearchPattern { get; private set; }
		
		/// <summary>
		/// Gets whether the search pattern should be interpreted case-sensitive.
		/// </summary>
		public bool MatchCase { get; private set; }
		
		/// <summary>
		/// Gets whether the search pattern should be interpreted as regular expression.
		/// </summary>
		public bool UseRegex { get; private set; }
		
		/// <summary>
		/// Gets whether the search pattern should only match whole words.
		/// </summary>
		public bool WholeWords { get; private set; }
		
		/// <summary>
		/// Creates a new SearchOptionsChangedEventArgs instance.
		/// </summary>
		public SearchOptionsChangedEventArgs(string searchPattern, bool matchCase, bool useRegex, bool wholeWords)
		{
			this.SearchPattern = searchPattern;
			this.MatchCase = matchCase;
			this.UseRegex = useRegex;
			this.WholeWords = wholeWords;
		}
	}
	
	class SearchPanelAdorner : Adorner
	{
		SearchPanel panel;
		
		public SearchPanelAdorner(TextArea textArea, SearchPanel panel)
			: base(textArea)
		{
			this.panel = panel;
			AddVisualChild(panel);
		}
		
		protected override int VisualChildrenCount {
			get { return 1; }
		}

		protected override Visual GetVisualChild(int index)
		{
			if (index != 0)
				throw new ArgumentOutOfRangeException();
			return panel;
		}
		
		protected override Size ArrangeOverride(Size finalSize)
		{
			panel.Arrange(new Rect(new Point(0, 0), finalSize));
			return new Size(panel.ActualWidth, panel.ActualHeight);
		}
	}
}