Search is not available for this dataset
id
stringlengths
1
8
text
stringlengths
72
9.81M
addition_count
int64
0
10k
commit_subject
stringlengths
0
3.7k
deletion_count
int64
0
8.43k
file_extension
stringlengths
0
32
lang
stringlengths
1
94
license
stringclasses
10 values
repo_name
stringlengths
9
59
10066450
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); //}); //Set's correct font size to linenumber this.PropertyChanged += (o, i) => { if (i.Property == FontSizeProperty) { if (LeftMargins.Count > 0 && LeftMargins[0] is LineNumberMargin lineNumberMargin) lineNumberMargin.InvalidateMeasure(); } }; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> InvalidateVisual <DFF> @@ -108,13 +108,6 @@ namespace AvaloniaEdit.Editing //}); //Set's correct font size to linenumber - this.PropertyChanged += (o, i) => - { - if (i.Property == FontSizeProperty) - { - if (LeftMargins.Count > 0 && LeftMargins[0] is LineNumberMargin lineNumberMargin) lineNumberMargin.InvalidateMeasure(); - } - }; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
0
InvalidateVisual
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066451
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); //}); //Set's correct font size to linenumber this.PropertyChanged += (o, i) => { if (i.Property == FontSizeProperty) { if (LeftMargins.Count > 0 && LeftMargins[0] is LineNumberMargin lineNumberMargin) lineNumberMargin.InvalidateMeasure(); } }; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> InvalidateVisual <DFF> @@ -108,13 +108,6 @@ namespace AvaloniaEdit.Editing //}); //Set's correct font size to linenumber - this.PropertyChanged += (o, i) => - { - if (i.Property == FontSizeProperty) - { - if (LeftMargins.Count > 0 && LeftMargins[0] is LineNumberMargin lineNumberMargin) lineNumberMargin.InvalidateMeasure(); - } - }; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
0
InvalidateVisual
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066452
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); //}); //Set's correct font size to linenumber this.PropertyChanged += (o, i) => { if (i.Property == FontSizeProperty) { if (LeftMargins.Count > 0 && LeftMargins[0] is LineNumberMargin lineNumberMargin) lineNumberMargin.InvalidateMeasure(); } }; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> InvalidateVisual <DFF> @@ -108,13 +108,6 @@ namespace AvaloniaEdit.Editing //}); //Set's correct font size to linenumber - this.PropertyChanged += (o, i) => - { - if (i.Property == FontSizeProperty) - { - if (LeftMargins.Count > 0 && LeftMargins[0] is LineNumberMargin lineNumberMargin) lineNumberMargin.InvalidateMeasure(); - } - }; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
0
InvalidateVisual
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066453
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); //}); //Set's correct font size to linenumber this.PropertyChanged += (o, i) => { if (i.Property == FontSizeProperty) { if (LeftMargins.Count > 0 && LeftMargins[0] is LineNumberMargin lineNumberMargin) lineNumberMargin.InvalidateMeasure(); } }; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> InvalidateVisual <DFF> @@ -108,13 +108,6 @@ namespace AvaloniaEdit.Editing //}); //Set's correct font size to linenumber - this.PropertyChanged += (o, i) => - { - if (i.Property == FontSizeProperty) - { - if (LeftMargins.Count > 0 && LeftMargins[0] is LineNumberMargin lineNumberMargin) lineNumberMargin.InvalidateMeasure(); - } - }; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
0
InvalidateVisual
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066454
<NME> TextArea.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using Avalonia; using Avalonia.Controls; using Avalonia.Controls.Presenters; using Avalonia.Controls.Primitives; using Avalonia.Data; using Avalonia.Input; using Avalonia.Input.TextInput; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Threading; using Avalonia.VisualTree; using AvaloniaEdit.Document; using AvaloniaEdit.Indentation; using AvaloniaEdit.Rendering; using AvaloniaEdit.Search; using AvaloniaEdit.Utils; using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Collections.ObjectModel; using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Linq; namespace AvaloniaEdit.Editing { /// <summary> /// Control that wraps a TextView and adds support for user input and the caret. /// </summary> public class TextArea : TemplatedControl, ITextEditorComponent, IRoutedCommandBindable, ILogicalScrollable { /// <summary> /// This is the extra scrolling space that occurs after the last line. /// </summary> private const int AdditionalVerticalScrollAmount = 2; private ILogicalScrollable _logicalScrollable; private readonly TextAreaTextInputMethodClient _imClient = new TextAreaTextInputMethodClient(); #region Constructor static TextArea() { KeyboardNavigation.TabNavigationProperty.OverrideDefaultValue<TextArea>(KeyboardNavigationMode.None); FocusableProperty.OverrideDefaultValue<TextArea>(true); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); AffectsArrange<TextArea>(OffsetProperty); AffectsRender<TextArea>(OffsetProperty); TextInputMethodClientRequestedEvent.AddClassHandler<TextArea>((ta, e) => { if (!ta.IsReadOnly) { e.Client = ta._imClient; } }); } /// <summary> /// Creates a new TextArea instance. /// </summary> public TextArea() : this(new TextView()) { AddHandler(KeyDownEvent, OnPreviewKeyDown, RoutingStrategies.Tunnel); AddHandler(KeyUpEvent, OnPreviewKeyUp, RoutingStrategies.Tunnel); } /// <summary> /// Creates a new TextArea instance. /// </summary> protected TextArea(TextView textView) { TextView = textView ?? throw new ArgumentNullException(nameof(textView)); _logicalScrollable = textView; Options = textView.Options; _selection = EmptySelection = new EmptySelection(this); textView.Services.AddService(this); textView.LineTransformers.Add(new SelectionColorizer(this)); textView.InsertLayer(new SelectionLayer(this), KnownLayer.Selection, LayerInsertionPosition.Replace); Caret = new Caret(this); Caret.PositionChanged += (sender, e) => RequestSelectionValidation(); //}); //Set's correct font size to linenumber this.PropertyChanged += (o, i) => { if (i.Property == FontSizeProperty) { if (LeftMargins.Count > 0 && LeftMargins[0] is LineNumberMargin lineNumberMargin) lineNumberMargin.InvalidateMeasure(); } }; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e) ActiveInputHandler = DefaultInputHandler; // TODO //textView.GetObservable(TextBlock.FontSizeProperty).Subscribe(_ => //{ // TextView.SetScrollOffset(new Vector(_offset.X, _offset.Y * TextView.DefaultLineHeight)); //}); } protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); if (e.NameScope.Find("PART_CP") is ContentPresenter contentPresenter) { contentPresenter.Content = TextView; } } internal void AddChild(IVisual visual) { VisualChildren.Add(visual); InvalidateArrange(); } internal void RemoveChild(IVisual visual) { VisualChildren.Remove(visual); } #endregion /// <summary> /// Defines the <see cref="IScrollable.Offset" /> property. /// </summary> public static readonly DirectProperty<TextArea, Vector> OffsetProperty = AvaloniaProperty.RegisterDirect<TextArea, Vector>( nameof(IScrollable.Offset), o => (o as IScrollable).Offset, (o, v) => (o as IScrollable).Offset = v); #region InputHandler management /// <summary> /// Gets the default input handler. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public TextAreaDefaultInputHandler DefaultInputHandler { get; } private ITextAreaInputHandler _activeInputHandler; private bool _isChangingInputHandler; /// <summary> /// Gets/Sets the active input handler. /// This property does not return currently active stacked input handlers. Setting this property detached all stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ITextAreaInputHandler ActiveInputHandler { get => _activeInputHandler; set { if (value != null && value.TextArea != this) throw new ArgumentException("The input handler was created for a different text area than this one."); if (_isChangingInputHandler) throw new InvalidOperationException("Cannot set ActiveInputHandler recursively"); if (_activeInputHandler != value) { _isChangingInputHandler = true; try { // pop the whole stack PopStackedInputHandler(StackedInputHandlers.LastOrDefault()); Debug.Assert(StackedInputHandlers.IsEmpty); _activeInputHandler?.Detach(); _activeInputHandler = value; value?.Attach(); } finally { _isChangingInputHandler = false; } ActiveInputHandlerChanged?.Invoke(this, EventArgs.Empty); } } } /// <summary> /// Occurs when the ActiveInputHandler property changes. /// </summary> public event EventHandler ActiveInputHandlerChanged; /// <summary> /// Gets the list of currently active stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public ImmutableStack<TextAreaStackedInputHandler> StackedInputHandlers { get; private set; } = ImmutableStack<TextAreaStackedInputHandler>.Empty; /// <summary> /// Pushes an input handler onto the list of stacked input handlers. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PushStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (inputHandler == null) throw new ArgumentNullException(nameof(inputHandler)); StackedInputHandlers = StackedInputHandlers.Push(inputHandler); inputHandler.Attach(); } /// <summary> /// Pops the stacked input handler (and all input handlers above it). /// If <paramref name="inputHandler"/> is not found in the currently stacked input handlers, or is null, this method /// does nothing. /// </summary> /// <remarks><inheritdoc cref="ITextAreaInputHandler"/></remarks> public void PopStackedInputHandler(TextAreaStackedInputHandler inputHandler) { if (StackedInputHandlers.Any(i => i == inputHandler)) { ITextAreaInputHandler oldHandler; do { oldHandler = StackedInputHandlers.Peek(); StackedInputHandlers = StackedInputHandlers.Pop(); oldHandler.Detach(); } while (oldHandler != inputHandler); } } #endregion #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <inheritdoc/> public event EventHandler DocumentChanged; /// <summary> /// Gets if the the document displayed by the text editor is readonly /// </summary> public bool IsReadOnly { get => ReadOnlySectionProvider == ReadOnlySectionDocument.Instance; } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.RemoveHandler(oldValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.RemoveHandler(oldValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.RemoveHandler(oldValue, OnUpdateFinished); } TextView.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnDocumentChanging); TextDocumentWeakEventManager.Changed.AddHandler(newValue, OnDocumentChanged); TextDocumentWeakEventManager.UpdateStarted.AddHandler(newValue, OnUpdateStarted); TextDocumentWeakEventManager.UpdateFinished.AddHandler(newValue, OnUpdateFinished); InvalidateArrange(); } // Reset caret location and selection: this is necessary because the caret/selection might be invalid // in the new document (e.g. if new document is shorter than the old document). Caret.Location = new TextLocation(1, 1); ClearSelection(); DocumentChanged?.Invoke(this, EventArgs.Empty); //CommandManager.InvalidateRequerySuggested(); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextArea>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// </summary> public TextEditorOptions Options { get => GetValue(OptionsProperty); set => SetValue(OptionsProperty, value); } /// <summary> /// Occurs when a text editor option has changed. /// </summary> public event PropertyChangedEventHandler OptionChanged; private void OnOptionChanged(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } /// <summary> /// Raises the <see cref="OptionChanged"/> event. /// </summary> protected virtual void OnOptionChanged(PropertyChangedEventArgs e) { OptionChanged?.Invoke(this, e); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextArea)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnOptionChanged); } TextView.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnOptionChanged); } OnOptionChanged(new PropertyChangedEventArgs(null)); } #endregion #region Caret handling on document changes private void OnDocumentChanging(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanging(); } private void OnDocumentChanged(object sender, DocumentChangeEventArgs e) { Caret.OnDocumentChanged(e); Selection = _selection.UpdateOnDocumentChange(e); } private void OnUpdateStarted(object sender, EventArgs e) { Document.UndoStack.PushOptional(new RestoreCaretAndSelectionUndoAction(this)); } private void OnUpdateFinished(object sender, EventArgs e) { Caret.OnDocumentUpdateFinished(); } private sealed class RestoreCaretAndSelectionUndoAction : IUndoableOperation { // keep textarea in weak reference because the IUndoableOperation is stored with the document private readonly WeakReference _textAreaReference; private readonly TextViewPosition _caretPosition; private readonly Selection _selection; public RestoreCaretAndSelectionUndoAction(TextArea textArea) { _textAreaReference = new WeakReference(textArea); // Just save the old caret position, no need to validate here. // If we restore it, we'll validate it anyways. _caretPosition = textArea.Caret.NonValidatedPosition; _selection = textArea.Selection; } public void Undo() { var textArea = (TextArea)_textAreaReference.Target; if (textArea != null) { textArea.Caret.Position = _caretPosition; textArea.Selection = _selection; } } public void Redo() { // redo=undo: we just restore the caret/selection state Undo(); } } #endregion #region TextView property /// <summary> /// Gets the text view used to display text in this text area. /// </summary> public TextView TextView { get; } #endregion #region Selection property internal readonly Selection EmptySelection; private Selection _selection; /// <summary> /// Occurs when the selection has changed. /// </summary> public event EventHandler SelectionChanged; /// <summary> /// Gets/Sets the selection in this text area. /// </summary> public Selection Selection { get => _selection; set { if (value == null) throw new ArgumentNullException(nameof(value)); if (value.TextArea != this) throw new ArgumentException("Cannot use a Selection instance that belongs to another text area."); if (!Equals(_selection, value)) { if (TextView != null) { var oldSegment = _selection.SurroundingSegment; var newSegment = value.SurroundingSegment; if (!Selection.EnableVirtualSpace && (_selection is SimpleSelection && value is SimpleSelection && oldSegment != null && newSegment != null)) { // perf optimization: // When a simple selection changes, don't redraw the whole selection, but only the changed parts. var oldSegmentOffset = oldSegment.Offset; var newSegmentOffset = newSegment.Offset; if (oldSegmentOffset != newSegmentOffset) { TextView.Redraw(Math.Min(oldSegmentOffset, newSegmentOffset), Math.Abs(oldSegmentOffset - newSegmentOffset)); } var oldSegmentEndOffset = oldSegment.EndOffset; var newSegmentEndOffset = newSegment.EndOffset; if (oldSegmentEndOffset != newSegmentEndOffset) { TextView.Redraw(Math.Min(oldSegmentEndOffset, newSegmentEndOffset), Math.Abs(oldSegmentEndOffset - newSegmentEndOffset)); } } else { TextView.Redraw(oldSegment); TextView.Redraw(newSegment); } } _selection = value; SelectionChanged?.Invoke(this, EventArgs.Empty); // a selection change causes commands like copy/paste/etc. to change status //CommandManager.InvalidateRequerySuggested(); } } } /// <summary> /// Clears the current selection. /// </summary> public void ClearSelection() { Selection = EmptySelection; } /// <summary> /// The <see cref="SelectionBrush"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionBrushProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionBrush"); /// <summary> /// Gets/Sets the background brush used for the selection. /// </summary> public IBrush SelectionBrush { get => GetValue(SelectionBrushProperty); set => SetValue(SelectionBrushProperty, value); } /// <summary> /// The <see cref="SelectionForeground"/> property. /// </summary> public static readonly StyledProperty<IBrush> SelectionForegroundProperty = AvaloniaProperty.Register<TextArea, IBrush>("SelectionForeground"); /// <summary> /// Gets/Sets the foreground brush used for selected text. /// </summary> public IBrush SelectionForeground { get => GetValue(SelectionForegroundProperty); set => SetValue(SelectionForegroundProperty, value); } /// <summary> /// The <see cref="SelectionBorder"/> property. /// </summary> public static readonly StyledProperty<Pen> SelectionBorderProperty = AvaloniaProperty.Register<TextArea, Pen>("SelectionBorder"); /// <summary> /// Gets/Sets the pen used for the border of the selection. /// </summary> public Pen SelectionBorder { get => GetValue(SelectionBorderProperty); set => SetValue(SelectionBorderProperty, value); } /// <summary> /// The <see cref="SelectionCornerRadius"/> property. /// </summary> public static readonly StyledProperty<double> SelectionCornerRadiusProperty = AvaloniaProperty.Register<TextArea, double>("SelectionCornerRadius", 3.0); /// <summary> /// Gets/Sets the corner radius of the selection. /// </summary> public double SelectionCornerRadius { get => GetValue(SelectionCornerRadiusProperty); set => SetValue(SelectionCornerRadiusProperty, value); } #endregion #region Force caret to stay inside selection private bool _ensureSelectionValidRequested; private int _allowCaretOutsideSelection; private void RequestSelectionValidation() { if (!_ensureSelectionValidRequested && _allowCaretOutsideSelection == 0) { _ensureSelectionValidRequested = true; Dispatcher.UIThread.Post(EnsureSelectionValid); } } /// <summary> /// Code that updates only the caret but not the selection can cause confusion when /// keys like 'Delete' delete the (possibly invisible) selected text and not the /// text around the caret. /// /// So we'll ensure that the caret is inside the selection. /// (when the caret is not in the selection, we'll clear the selection) /// /// This method is invoked using the Dispatcher so that code may temporarily violate this rule /// (e.g. most 'extend selection' methods work by first setting the caret, then the selection), /// it's sufficient to fix it after any event handlers have run. /// </summary> private void EnsureSelectionValid() { _ensureSelectionValidRequested = false; if (_allowCaretOutsideSelection == 0) { if (!_selection.IsEmpty && !_selection.Contains(Caret.Offset)) { ClearSelection(); } } } /// <summary> /// Temporarily allows positioning the caret outside the selection. /// Dispose the returned IDisposable to revert the allowance. /// </summary> /// <remarks> /// The text area only forces the caret to be inside the selection when other events /// have finished running (using the dispatcher), so you don't have to use this method /// for temporarily positioning the caret in event handlers. /// This method is only necessary if you want to run the dispatcher, e.g. if you /// perform a drag'n'drop operation. /// </remarks> public IDisposable AllowCaretOutsideSelection() { VerifyAccess(); _allowCaretOutsideSelection++; return new CallbackOnDispose( delegate { VerifyAccess(); _allowCaretOutsideSelection--; RequestSelectionValidation(); }); } #endregion #region Properties /// <summary> /// Gets the Caret used for this text area. /// </summary> public Caret Caret { get; } /// <summary> /// Scrolls the text view so that the requested line is in the middle. /// If the textview can be scrolled. /// </summary> /// <param name="line">The line to scroll to.</param> public void ScrollToLine (int line) { var viewPortLines = (int)(this as IScrollable).Viewport.Height; if (viewPortLines < Document.LineCount) { ScrollToLine(line, 2, viewPortLines / 2); } } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesEitherSide">The number of lines above and below.</param> public void ScrollToLine(int line, int linesEitherSide) { ScrollToLine(line, linesEitherSide, linesEitherSide); } /// <summary> /// Scrolls the textview to a position with n lines above and below it. /// </summary> /// <param name="line">the requested line number.</param> /// <param name="linesAbove">The number of lines above.</param> /// <param name="linesBelow">The number of lines below.</param> public void ScrollToLine(int line, int linesAbove, int linesBelow) { var offset = line - linesAbove; if (offset < 0) { offset = 0; } this.BringIntoView(new Rect(1, offset, 0, 1)); offset = line + linesBelow; if (offset >= 0) { this.BringIntoView(new Rect(1, offset, 0, 1)); } } private void CaretPositionChanged(object sender, EventArgs e) { if (TextView == null) return; TextView.HighlightedLine = Caret.Line; ScrollToLine(Caret.Line, 2); Dispatcher.UIThread.InvokeAsync(() => { (this as ILogicalScrollable).RaiseScrollInvalidated(EventArgs.Empty); }); } public static readonly DirectProperty<TextArea, ObservableCollection<IControl>> LeftMarginsProperty = AvaloniaProperty.RegisterDirect<TextArea, ObservableCollection<IControl>>(nameof(LeftMargins), c => c.LeftMargins); /// <summary> /// Gets the collection of margins displayed to the left of the text view. /// </summary> public ObservableCollection<IControl> LeftMargins { get; } = new ObservableCollection<IControl>(); private void LeftMargins_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e) { if (e.OldItems != null) { foreach (var c in e.OldItems.OfType<ITextViewConnect>()) { c.RemoveFromTextView(TextView); } } if (e.NewItems != null) { foreach (var c in e.NewItems.OfType<ITextViewConnect>()) { c.AddToTextView(TextView); } } } private IReadOnlySectionProvider _readOnlySectionProvider = NoReadOnlySections.Instance; /// <summary> /// Gets/Sets an object that provides read-only sections for the text area. /// </summary> public IReadOnlySectionProvider ReadOnlySectionProvider { get => _readOnlySectionProvider; set => _readOnlySectionProvider = value ?? throw new ArgumentNullException(nameof(value)); } /// <summary> /// The <see cref="RightClickMovesCaret"/> property. /// </summary> public static readonly StyledProperty<bool> RightClickMovesCaretProperty = AvaloniaProperty.Register<TextArea, bool>(nameof(RightClickMovesCaret), false); /// <summary> /// Determines whether caret position should be changed to the mouse position when you right click or not. /// </summary> public bool RightClickMovesCaret { get => GetValue(RightClickMovesCaretProperty); set => SetValue(RightClickMovesCaretProperty, value); } #endregion #region Focus Handling (Show/Hide Caret) protected override void OnPointerPressed(PointerPressedEventArgs e) { base.OnPointerPressed(e); Focus(); } protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); Caret.Show(); _imClient.SetTextArea(this); } protected override void OnLostFocus(RoutedEventArgs e) { base.OnLostFocus(e); Caret.Hide(); _imClient.SetTextArea(null); } #endregion #region OnTextInput / RemoveSelectedText / ReplaceSelectionWithText /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately before the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntering; /// <summary> /// Occurs when the TextArea receives text input. /// but occurs immediately after the TextArea handles the TextInput event. /// </summary> public event EventHandler<TextInputEventArgs> TextEntered; /// <summary> /// Raises the TextEntering event. /// </summary> protected virtual void OnTextEntering(TextInputEventArgs e) { TextEntering?.Invoke(this, e); } /// <summary> /// Raises the TextEntered event. /// </summary> protected virtual void OnTextEntered(TextInputEventArgs e) { TextEntered?.Invoke(this, e); } protected override void OnTextInput(TextInputEventArgs e) { base.OnTextInput(e); if (!e.Handled && Document != null) { if (string.IsNullOrEmpty(e.Text) || e.Text == "\x1b" || e.Text == "\b" || e.Text == "\u007f") { // TODO: check this // ASCII 0x1b = ESC. // produces a TextInput event with that old ASCII control char // when Escape is pressed. We'll just ignore it. // A deadkey followed by backspace causes a textinput event for the BS character. // Similarly, some shortcuts like Alt+Space produce an empty TextInput event. // We have to ignore those (not handle them) to keep the shortcut working. return; } HideMouseCursor(); PerformTextInput(e); e.Handled = true; } } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(string text) { var e = new TextInputEventArgs { Text = text, RoutedEvent = TextInputEvent }; PerformTextInput(e); } /// <summary> /// Performs text input. /// This raises the <see cref="TextEntering"/> event, replaces the selection with the text, /// and then raises the <see cref="TextEntered"/> event. /// </summary> public void PerformTextInput(TextInputEventArgs e) { if (e == null) throw new ArgumentNullException(nameof(e)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); OnTextEntering(e); if (!e.Handled) { if (e.Text == "\n" || e.Text == "\r" || e.Text == "\r\n") ReplaceSelectionWithNewLine(); else { // TODO //if (OverstrikeMode && Selection.IsEmpty && Document.GetLineByNumber(Caret.Line).EndOffset > Caret.Offset) // EditingCommands.SelectRightByCharacter.Execute(null, this); ReplaceSelectionWithText(e.Text); } OnTextEntered(e); Caret.BringCaretToView(); } } private void ReplaceSelectionWithNewLine() { var newLine = TextUtilities.GetNewLineFromDocument(Document, Caret.Line); using (Document.RunUpdate()) { ReplaceSelectionWithText(newLine); if (IndentationStrategy != null) { var line = Document.GetLineByNumber(Caret.Line); var deletable = GetDeletableSegments(line); if (deletable.Length == 1 && deletable[0].Offset == line.Offset && deletable[0].Length == line.Length) { // use indentation strategy only if the line is not read-only IndentationStrategy.IndentLine(Document, line); } } } } internal void RemoveSelectedText() { if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(string.Empty); #if DEBUG if (!_selection.IsEmpty) { foreach (var s in _selection.Segments) { Debug.Assert(!ReadOnlySectionProvider.GetDeletableSegments(s).Any()); } } #endif } internal void ReplaceSelectionWithText(string newText) { if (newText == null) throw new ArgumentNullException(nameof(newText)); if (Document == null) throw ThrowUtil.NoDocumentAssigned(); _selection.ReplaceSelectionWithText(newText); } internal ISegment[] GetDeletableSegments(ISegment segment) { var deletableSegments = ReadOnlySectionProvider.GetDeletableSegments(segment); if (deletableSegments == null) throw new InvalidOperationException("ReadOnlySectionProvider.GetDeletableSegments returned null"); var array = deletableSegments.ToArray(); var lastIndex = segment.Offset; foreach (var t in array) { if (t.Offset < lastIndex) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); lastIndex = t.EndOffset; } if (lastIndex > segment.EndOffset) throw new InvalidOperationException("ReadOnlySectionProvider returned incorrect segments (outside of input segment / wrong order)"); return array; } #endregion #region IndentationStrategy property /// <summary> /// IndentationStrategy property. /// </summary> public static readonly StyledProperty<IIndentationStrategy> IndentationStrategyProperty = AvaloniaProperty.Register<TextArea, IIndentationStrategy>("IndentationStrategy", new DefaultIndentationStrategy()); /// <summary> /// Gets/Sets the indentation strategy used when inserting new lines. /// </summary> public IIndentationStrategy IndentationStrategy { get => GetValue(IndentationStrategyProperty); set => SetValue(IndentationStrategyProperty, value); } #endregion #region OnKeyDown/OnKeyUp // Make life easier for text editor extensions that use a different cursor based on the pressed modifier keys. /// <inheritdoc/> protected override void OnKeyDown(KeyEventArgs e) { base.OnKeyDown(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyDown(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyDown(e); } } /// <inheritdoc/> protected override void OnKeyUp(KeyEventArgs e) { base.OnKeyUp(e); TextView.InvalidateCursorIfPointerWithinTextView(); } private void OnPreviewKeyUp(object sender, KeyEventArgs e) { foreach (var h in StackedInputHandlers) { if (e.Handled) break; h.OnPreviewKeyUp(e); } } #endregion #region Hide Mouse Cursor While Typing private bool _isMouseCursorHidden; private void AttachTypingEvents() { // Use the PreviewMouseMove event in case some other editor layer consumes the MouseMove event (e.g. SD's InsertionCursorLayer) PointerEntered += delegate { ShowMouseCursor(); }; PointerExited += delegate { ShowMouseCursor(); }; } private void ShowMouseCursor() { if (_isMouseCursorHidden) { _isMouseCursorHidden = false; } } private void HideMouseCursor() { if (Options.HideCursorWhileTyping && !_isMouseCursorHidden && IsPointerOver) { _isMouseCursorHidden = true; } } #endregion #region Overstrike mode /// <summary> /// The <see cref="OverstrikeMode"/> dependency property. /// </summary> public static readonly StyledProperty<bool> OverstrikeModeProperty = AvaloniaProperty.Register<TextArea, bool>("OverstrikeMode"); /// <summary> /// Gets/Sets whether overstrike mode is active. /// </summary> public bool OverstrikeMode { get => GetValue(OverstrikeModeProperty); set => SetValue(OverstrikeModeProperty, value); } #endregion /// <inheritdoc/> protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == SelectionBrushProperty || change.Property == SelectionBorderProperty || change.Property == SelectionForegroundProperty || change.Property == SelectionCornerRadiusProperty) { TextView.Redraw(); } else if (change.Property == OverstrikeModeProperty) { Caret.UpdateIfVisible(); } } /// <summary> /// Gets the requested service. /// </summary> /// <returns>Returns the requested service instance, or null if the service cannot be found.</returns> public virtual object GetService(Type serviceType) { return TextView.GetService(serviceType); } /// <summary> /// Occurs when text inside the TextArea was copied. /// </summary> public event EventHandler<TextEventArgs> TextCopied; event EventHandler ILogicalScrollable.ScrollInvalidated { add { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated += value; } remove { if (_logicalScrollable != null) _logicalScrollable.ScrollInvalidated -= value; } } internal void OnTextCopied(TextEventArgs e) { TextCopied?.Invoke(this, e); } public IList<RoutedCommandBinding> CommandBindings { get; } = new List<RoutedCommandBinding>(); bool ILogicalScrollable.IsLogicalScrollEnabled => _logicalScrollable?.IsLogicalScrollEnabled ?? default(bool); Size ILogicalScrollable.ScrollSize => _logicalScrollable?.ScrollSize ?? default(Size); Size ILogicalScrollable.PageScrollSize => _logicalScrollable?.PageScrollSize ?? default(Size); Size IScrollable.Extent => _logicalScrollable?.Extent ?? default(Size); Vector IScrollable.Offset { get => _logicalScrollable?.Offset ?? default(Vector); set { if (_logicalScrollable != null) { _logicalScrollable.Offset = value; } } } Size IScrollable.Viewport => _logicalScrollable?.Viewport ?? default(Size); bool ILogicalScrollable.CanHorizontallyScroll { get => _logicalScrollable?.CanHorizontallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanHorizontallyScroll = value; } } } bool ILogicalScrollable.CanVerticallyScroll { get => _logicalScrollable?.CanVerticallyScroll ?? default(bool); set { if (_logicalScrollable != null) { _logicalScrollable.CanVerticallyScroll = value; } } } public bool BringIntoView(IControl target, Rect targetRect) => _logicalScrollable?.BringIntoView(target, targetRect) ?? default(bool); IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from) => _logicalScrollable?.GetControlInDirection(direction, from); public void RaiseScrollInvalidated(EventArgs e) { _logicalScrollable?.RaiseScrollInvalidated(e); } private class TextAreaTextInputMethodClient : ITextInputMethodClient { private TextArea _textArea; public TextAreaTextInputMethodClient() { } public event EventHandler CursorRectangleChanged; public event EventHandler TextViewVisualChanged; public event EventHandler SurroundingTextChanged; public Rect CursorRectangle { get { if(_textArea == null) { return Rect.Empty; } var transform = _textArea.TextView.TransformToVisual(_textArea); if (transform == null) { return default; } var rect = _textArea.Caret.CalculateCaretRectangle().TransformToAABB(transform.Value); return rect; } } public IVisual TextViewVisual => _textArea; public bool SupportsPreedit => false; public bool SupportsSurroundingText => true; public TextInputMethodSurroundingText SurroundingText { get { if(_textArea == null) { return default; } var lineIndex = _textArea.Caret.Line; var position = _textArea.Caret.Position; var documentLine = _textArea.Document.GetLineByNumber(lineIndex); var text = _textArea.Document.GetText(documentLine.Offset, documentLine.Length); return new TextInputMethodSurroundingText { AnchorOffset = 0, CursorOffset = position.Column, Text = text }; } } public void SetTextArea(TextArea textArea) { if(_textArea != null) { _textArea.Caret.PositionChanged -= Caret_PositionChanged; _textArea.SelectionChanged -= TextArea_SelectionChanged; } _textArea = textArea; if(_textArea != null) { _textArea.Caret.PositionChanged += Caret_PositionChanged; _textArea.SelectionChanged += TextArea_SelectionChanged; } TextViewVisualChanged?.Invoke(this, EventArgs.Empty); CursorRectangleChanged?.Invoke(this, EventArgs.Empty); } private void Caret_PositionChanged(object sender, EventArgs e) { CursorRectangleChanged?.Invoke(this, e); } private void TextArea_SelectionChanged(object sender, EventArgs e) { SurroundingTextChanged?.Invoke(this, e); } public void SelectInSurroundingText(int start, int end) { if(_textArea == null) { return; } var selection = _textArea.Selection; _textArea.Selection = _textArea.Selection.StartSelectionOrSetEndpoint( new TextViewPosition(selection.StartPosition.Line, start), new TextViewPosition(selection.StartPosition.Line, end)); } public void SetPreeditText(string text) { } } } /// <summary> /// EventArgs with text. /// </summary> public class TextEventArgs : EventArgs { /// <summary> /// Gets the text. /// </summary> public string Text { get; } /// <summary> /// Creates a new TextEventArgs instance. /// </summary> public TextEventArgs(string text) { Text = text ?? throw new ArgumentNullException(nameof(text)); } } } <MSG> InvalidateVisual <DFF> @@ -108,13 +108,6 @@ namespace AvaloniaEdit.Editing //}); //Set's correct font size to linenumber - this.PropertyChanged += (o, i) => - { - if (i.Property == FontSizeProperty) - { - if (LeftMargins.Count > 0 && LeftMargins[0] is LineNumberMargin lineNumberMargin) lineNumberMargin.InvalidateMeasure(); - } - }; } protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
0
InvalidateVisual
7
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066455
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066456
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066457
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066458
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066459
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066460
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066461
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066462
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066463
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066464
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066465
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066466
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066467
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066468
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066469
<NME> MainWindow.xaml.cs <BEF> using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Runtime.CompilerServices; using Avalonia.Controls; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Markup.Xaml; using Avalonia.Media; using Avalonia.Media.Imaging; using AvaloniaEdit.CodeCompletion; using AvaloniaEdit.Demo.Resources; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Folding; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using TextMateSharp.Grammars; using Avalonia.Diagnostics; namespace AvaloniaEdit.Demo { using Pair = KeyValuePair<int, Control>; public class MainWindow : Window { private readonly TextEditor _textEditor; private FoldingManager _foldingManager; private readonly TextMate.TextMate.Installation _textMateInstallation; private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); private IPopupImpl impl; public MainWindow() { private TextBlock _statusTextBlock; private ElementGenerator _generator = new ElementGenerator(); private RegistryOptions _registryOptions; private int _currentTheme = (int)ThemeName.DarkPlus; public MainWindow() { InitializeComponent(); _textEditor = this.FindControl<TextEditor>("Editor"); _textEditor.HorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Visible; _textEditor.Background = Brushes.Transparent; _textEditor.ShowLineNumbers = true; _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); impl = PlatformManager.CreateWindow().CreatePopup(); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; } }; _textEditor.TextArea.Background = this.Background; _textEditor.TextArea.TextEntered += textEditor_TextArea_TextEntered; _textEditor.TextArea.TextEntering += textEditor_TextArea_TextEntering; _textEditor.Options.ShowBoxForControlCharacters = true; _textEditor.Options.ColumnRulerPositions = new List<int>() { 80, 100 }; _textEditor.TextArea.IndentationStrategy = new Indentation.CSharp.CSharpIndentationStrategy(_textEditor.Options); _textEditor.TextArea.Caret.PositionChanged += Caret_PositionChanged; _textEditor.TextArea.RightClickMovesCaret = true; _addControlButton = this.FindControl<Button>("addControlBtn"); _addControlButton.Click += AddControlButton_Click; _clearControlButton = this.FindControl<Button>("clearControlBtn"); _clearControlButton.Click += ClearControlButton_Click; _changeThemeButton = this.FindControl<Button>("changeThemeBtn"); _changeThemeButton.Click += ChangeThemeButton_Click; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); _registryOptions = new RegistryOptions( (ThemeName)_currentTheme); _textMateInstallation = _textEditor.InstallTextMate(_registryOptions); Language csharpLanguage = _registryOptions.GetLanguageByExtension(".cs"); _syntaxModeCombo = this.FindControl<ComboBox>("syntaxModeCombo"); _syntaxModeCombo.Items = _registryOptions.GetAvailableLanguages(); _syntaxModeCombo.SelectedItem = csharpLanguage; _syntaxModeCombo.SelectionChanged += SyntaxModeCombo_SelectionChanged; string scopeName = _registryOptions.GetScopeByLanguageId(csharpLanguage.Id); _textEditor.Document = new TextDocument( "// AvaloniaEdit supports displaying control chars: \a or \b or \v" + Environment.NewLine + "// AvaloniaEdit supports displaying underline and strikethrough" + Environment.NewLine + ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(_registryOptions.GetScopeByLanguageId(csharpLanguage.Id)); _textEditor.TextArea.TextView.LineTransformers.Add(new UnderlineAndStrikeThroughTransformer()); _statusTextBlock = this.Find<TextBlock>("StatusText"); this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return; if (i.Delta.Y > 0) _textEditor.FontSize++; else _textEditor.FontSize = _textEditor.FontSize > 1 ? _textEditor.FontSize - 1 : 1; }, RoutingStrategies.Bubble, true); } private void Caret_PositionChanged(object sender, EventArgs e) { _statusTextBlock.Text = string.Format("Line {0} Column {1}", _textEditor.TextArea.Caret.Line, _textEditor.TextArea.Caret.Column); } protected override void OnClosed(EventArgs e) { base.OnClosed(e); _textMateInstallation.Dispose(); } private void SyntaxModeCombo_SelectionChanged(object sender, SelectionChangedEventArgs e) { RemoveUnderlineAndStrikethroughTransformer(); Language language = (Language)_syntaxModeCombo.SelectedItem; if (_foldingManager != null) { _foldingManager.Clear(); FoldingManager.Uninstall(_foldingManager); } string scopeName = _registryOptions.GetScopeByLanguageId(language.Id); _textMateInstallation.SetGrammar(null); _textEditor.Document = new TextDocument(ResourceLoader.LoadSampleFile(scopeName)); _textMateInstallation.SetGrammar(scopeName); if (language.Id == "xml") { _foldingManager = FoldingManager.Install(_textEditor.TextArea); var strategy = new XmlFoldingStrategy(); strategy.UpdateFoldings(_foldingManager, _textEditor.Document); return; } } private void RemoveUnderlineAndStrikethroughTransformer() { for (int i = _textEditor.TextArea.TextView.LineTransformers.Count - 1; i >= 0; i--) { if (_textEditor.TextArea.TextView.LineTransformers[i] is UnderlineAndStrikeThroughTransformer) { _textEditor.TextArea.TextView.LineTransformers.RemoveAt(i); } } } private void ChangeThemeButton_Click(object sender, RoutedEventArgs e) { _currentTheme = (_currentTheme + 1) % Enum.GetNames(typeof(ThemeName)).Length; _textMateInstallation.SetTheme(_registryOptions.LoadTheme( (ThemeName)_currentTheme)); } private void InitializeComponent() { AvaloniaXamlLoader.Load(this); } private void AddControlButton_Click(object sender, RoutedEventArgs e) { _generator.controls.Add(new Pair(_textEditor.CaretOffset, new Button() { Content = "Click me", Cursor = Cursor.Default })); _textEditor.TextArea.TextView.Redraw(); } private void ClearControlButton_Click(object sender, RoutedEventArgs e) { //TODO: delete elements using back key _generator.controls.Clear(); _textEditor.TextArea.TextView.Redraw(); } private void textEditor_TextArea_TextEntering(object sender, TextInputEventArgs e) { if (e.Text.Length > 0 && _completionWindow != null) { if (!char.IsLetterOrDigit(e.Text[0])) { // Whenever a non-letter is typed while the completion window is open, // insert the currently selected element. _completionWindow.CompletionList.RequestInsertion(e); } } _insightWindow?.Hide(); // Do not set e.Handled=true. // We still want to insert the character that was typed. } private void textEditor_TextArea_TextEntered(object sender, TextInputEventArgs e) { if (e.Text == ".") { _completionWindow = new CompletionWindow(_textEditor.TextArea); _completionWindow.Closed += (o, args) => _completionWindow = null; var data = _completionWindow.CompletionList.CompletionData; data.Add(new MyCompletionData("Item1")); data.Add(new MyCompletionData("Item2")); data.Add(new MyCompletionData("Item3")); data.Add(new MyCompletionData("Item4")); data.Add(new MyCompletionData("Item5")); data.Add(new MyCompletionData("Item6")); data.Add(new MyCompletionData("Item7")); data.Add(new MyCompletionData("Item8")); data.Add(new MyCompletionData("Item9")); data.Add(new MyCompletionData("Item10")); data.Add(new MyCompletionData("Item11")); data.Add(new MyCompletionData("Item12")); data.Add(new MyCompletionData("Item13")); _completionWindow.Show(); } else if (e.Text == "(") { _insightWindow = new OverloadInsightWindow(_textEditor.TextArea); _insightWindow.Closed += (o, args) => _insightWindow = null; _insightWindow.Provider = new MyOverloadProvider(new[] { ("Method1(int, string)", "Method1 description"), ("Method2(int)", "Method2 description"), ("Method3(string)", "Method3 description"), }); _insightWindow.Show(); } } class UnderlineAndStrikeThroughTransformer : DocumentColorizingTransformer { protected override void ColorizeLine(DocumentLine line) { if (line.LineNumber == 2) { string lineText = this.CurrentContext.Document.GetText(line); int indexOfUnderline = lineText.IndexOf("underline"); int indexOfStrikeThrough = lineText.IndexOf("strikethrough"); if (indexOfUnderline != -1) { ChangeLinePart( line.Offset + indexOfUnderline, line.Offset + indexOfUnderline + "underline".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Underline[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Underline); } } ); } if (indexOfStrikeThrough != -1) { ChangeLinePart( line.Offset + indexOfStrikeThrough, line.Offset + indexOfStrikeThrough + "strikethrough".Length, visualLine => { if (visualLine.TextRunProperties.TextDecorations != null) { var textDecorations = new TextDecorationCollection(visualLine.TextRunProperties.TextDecorations) { TextDecorations.Strikethrough[0] }; visualLine.TextRunProperties.SetTextDecorations(textDecorations); } else { visualLine.TextRunProperties.SetTextDecorations(TextDecorations.Strikethrough); } } ); } } } } private class MyOverloadProvider : IOverloadProvider { private readonly IList<(string header, string content)> _items; private int _selectedIndex; public MyOverloadProvider(IList<(string header, string content)> items) { _items = items; SelectedIndex = 0; } public int SelectedIndex { get => _selectedIndex; set { _selectedIndex = value; OnPropertyChanged(); // ReSharper disable ExplicitCallerInfoArgument OnPropertyChanged(nameof(CurrentHeader)); OnPropertyChanged(nameof(CurrentContent)); // ReSharper restore ExplicitCallerInfoArgument } } public int Count => _items.Count; public string CurrentIndexText => null; public object CurrentHeader => _items[SelectedIndex].header; public object CurrentContent => _items[SelectedIndex].content; public event PropertyChangedEventHandler PropertyChanged; private void OnPropertyChanged([CallerMemberName] string propertyName = null) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } } public class MyCompletionData : ICompletionData { public MyCompletionData(string text) { Text = text; } public IBitmap Image => null; public string Text { get; } // Use this property if you want to show a fancy UIElement in the list. public object Content => Text; public object Description => "Description for " + Text; public double Priority { get; } = 0; public void Complete(TextArea textArea, ISegment completionSegment, EventArgs insertionRequestEventArgs) { textArea.Document.Replace(completionSegment, Text); } } class ElementGenerator : VisualLineElementGenerator, IComparer<Pair> { public List<Pair> controls = new List<Pair>(); /// <summary> /// Gets the first interested offset using binary search /// </summary> /// <returns>The first interested offset.</returns> /// <param name="startOffset">Start offset.</param> public override int GetFirstInterestedOffset(int startOffset) { int pos = controls.BinarySearch(new Pair(startOffset, null), this); if (pos < 0) pos = ~pos; if (pos < controls.Count) return controls[pos].Key; else return -1; } public override VisualLineElement ConstructElement(int offset) { int pos = controls.BinarySearch(new Pair(offset, null), this); if (pos >= 0) return new InlineObjectElement(0, controls[pos].Value); else return null; } int IComparer<Pair>.Compare(Pair x, Pair y) { return x.Key.CompareTo(y.Key); } } } } <MSG> remove wierd code causing crash on osx. <DFF> @@ -30,7 +30,6 @@ namespace AvaloniaEdit.Demo private Button _addControlBtn; private Button _clearControlBtn; private ElementGenerator _generator = new ElementGenerator(); - private IPopupImpl impl; public MainWindow() { @@ -51,9 +50,7 @@ namespace AvaloniaEdit.Demo _clearControlBtn.Click += _clearControlBtn_Click; ; _textEditor.TextArea.TextView.ElementGenerators.Add(_generator); - - impl = PlatformManager.CreateWindow().CreatePopup(); - + this.AddHandler(PointerWheelChangedEvent, (o, i) => { if (i.KeyModifiers != KeyModifiers.Control) return;
1
remove wierd code causing crash on osx.
4
.cs
Demo/MainWindow
mit
AvaloniaUI/AvaloniaEdit
10066470
<NME> README.md <BEF> # FruitMachine [![Build Status](https://api.travis-ci.com/ftlabs/fruitmachine.svg)](https://travis-ci.com/ftlabs/fruitmachine) [![Coverage Status](https://coveralls.io/repos/ftlabs/fruitmachine/badge.png)](https://coveralls.io/r/ftlabs/fruitmachine) A lightweight component layout engine for client and server. FruitMachine is designed to build rich interactive layouts from modular, reusable components. It's light and unopinionated so that it can be applied to almost any layout problem. FruitMachine is currently powering the [FT Web App](http://apps.ft.com/ftwebapp/). ```js // Define a module var Apple = fruitmachine.define({ name: 'apple', template: function(){ return 'hello' } }); // Create an instance var apple = new Apple(); // Render & inject into DOM apple .render() .inject(document.body); apple.el.outerHTML; //=> <div class="apple">hello</div> ``` ## Installation ``` $ npm install fruitmachine ``` or ``` $ bower install fruitmachine ``` or Download the [production version][min] (~3k gzipped) or the [development version][max]. [min]: http://github.com/ftlabs/fruitmachine/raw/master/build/fruitmachine.min.js [max]: http://github.com/ftlabs/fruitmachine/raw/master/build/fruitmachine.js ## Examples - [Article viewer](http://ftlabs.github.io/fruitmachine/examples/article-viewer/) - [TODO](http://ftlabs.github.io/fruitmachine/examples/todo/) ## Documentation - [Introduction](docs/introduction.md) - [Getting started](docs/getting-started.md) - [Defining modules](docs/defining-modules.md) - [Slots](docs/slots.md) - [View assembly](docs/layout-assembly.md) - [Instantiation](docs/module-instantiation.md) - [Templates](docs/templates.md) - [Template markup](docs/template-markup.md) - [Rendering](docs/rendering.md) - [DOM injection](docs/injection.md) - [The module element](docs/module-el.md) - [Queries](docs/queries.md) - [Helpers](docs/module-helpers.md) - [Removing & destroying](docs/removing-and-destroying.md) - [Extending](docs/extending-modules.md) - [Server-side rendering](docs/server-side-rendering.md) - [API](docs/api.md) - [Events](docs/events.md) ## Tests #### With PhantomJS ``` $ npm install $ npm test ``` #### Without PhantomJS ``` $ node_modules/.bin/buster-static ``` ...then visit http://localhost:8282/ in browser ## Author - **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage) ## Contributors - **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage) - **Matt Andrews** - [@matthew-andrews](http://github.com/matthew-andrews) ## License Copyright (c) 2018 The Financial Times Limited Licensed under the MIT license. ## Credits and collaboration FruitMachine is largely unmaintained/finished. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request. <MSG> New build <DFF> @@ -11,13 +11,11 @@ var Apple = fruitmachine.define({ template: function(){ return 'hello' } }); -// Create an instance +// Create a module var apple = new Apple(); -// Render & inject into DOM -apple - .render() - .inject(document.body); +// Render it +apple.render(); apple.el.outerHTML; //=> <div class="apple">hello</div> @@ -37,7 +35,7 @@ $ bower install fruitmachine or -Download the [production version][min] (~3k gzipped) or the [development version][max]. +Download the [production version][min] (~2k gzipped) or the [development version][max]. [min]: http://github.com/ftlabs/fruitmachine/raw/master/build/fruitmachine.min.js [max]: http://github.com/ftlabs/fruitmachine/raw/master/build/fruitmachine.js
4
New build
6
.md
md
mit
ftlabs/fruitmachine
10066471
<NME> fruitmachine.js <BEF> /*jslint browser:true, node:true*/ /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * Options: * * - `Model` A model constructor to use (must have `.toJSON()`) * * @param {Object} options */ module.exports = function(options) { /** * Shortcut method for * creating lazy views. * * @param {Object} options * @return {Module} */ function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); } throw new Error("Unable to find module '" + options.module + "'"); } fm.create = module.exports; fm.Model = options.Model; fm.Events = events; fm.Module = mod(fm); fm.define = define(fm); fm.util = utils; fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; }); } // If this is already setup, call // `teardown` first so that we don't // duplicate event bindings and shizzle. if (this.isSetup) this.teardown({ shallow: true }); // Attempt to fetch the // view's root element this.getElement(); this.trigger('setup'); this.onSetup(); // Flag view as 'setup' <MSG> Halt setup if no route element is found <DFF> @@ -544,16 +544,20 @@ }); } + // Attempt to fetch the view's + // root element. Don't continue + // if no route element is found. + if (!this.getElement()) return this; + // If this is already setup, call // `teardown` first so that we don't // duplicate event bindings and shizzle. if (this.isSetup) this.teardown({ shallow: true }); - // Attempt to fetch the - // view's root element - this.getElement(); - + // Fire the `setup` event hook this.trigger('setup'); + + // Run onSetup custom function this.onSetup(); // Flag view as 'setup'
8
Halt setup if no route element is found
4
.js
js
mit
ftlabs/fruitmachine
10066472
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066473
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066474
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066475
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066476
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066477
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066478
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066479
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066480
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066481
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066482
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066483
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066484
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066485
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066486
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; EditorOnDocumentChanged(editor, EventArgs.Empty); } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; InvalidateLineRange( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { public override string GetLineText(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }).GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> prevent deadlock. <DFF> @@ -16,7 +16,7 @@ namespace AvaloniaEdit.TextMate { _editor = editor; _editor.DocumentChanged += EditorOnDocumentChanged; - + EditorOnDocumentChanged(editor, EventArgs.Empty); } @@ -99,14 +99,22 @@ namespace AvaloniaEdit.TextMate public override string GetLineText(int lineIndex) { - return Dispatcher.UIThread.InvokeAsync(() => + if (Dispatcher.UIThread.CheckAccess()) { return _document.GetText(_document.Lines[lineIndex]); - }).GetAwaiter().GetResult(); + } + + return Dispatcher.UIThread.InvokeAsync(() => { return _document.GetText(_document.Lines[lineIndex]); }) + .GetAwaiter().GetResult(); } public override int GetLineLength(int lineIndex) { + if (Dispatcher.UIThread.CheckAccess()) + { + return _document.Lines[lineIndex].Length; + } + return Dispatcher.UIThread.InvokeAsync(() => { return _document.Lines[lineIndex].Length;
11
prevent deadlock.
3
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066487
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066488
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066489
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066490
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066491
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066492
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066493
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066494
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066495
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066496
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066497
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066498
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066499
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066500
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066501
<NME> SingleCharacterElementGenerator.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Media.TextFormatting; using Avalonia.Utilities; using AvaloniaEdit.Document; using AvaloniaEdit.Utils; using LogicalDirection = AvaloniaEdit.Document.LogicalDirection; namespace AvaloniaEdit.Rendering { // This class is internal because it does not need to be accessed by the user - it can be configured using TextEditorOptions. /// <summary> /// Element generator that displays · for spaces and » for tabs and a box for control characters. /// </summary> /// <remarks> /// This element generator is present in every TextView by default; the enabled features can be configured using the /// <see cref="TextEditorOptions"/>. /// </remarks> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] internal sealed class SingleCharacterElementGenerator : VisualLineElementGenerator, IBuiltinElementGenerator { /// <summary> /// Gets/Sets whether to show · for spaces. /// </summary> public bool ShowSpaces { get; set; } /// <summary> /// Gets/Sets whether to show » for tabs. /// </summary> public bool ShowTabs { get; set; } /// <summary> /// Gets/Sets whether to show a box with the hex code for control characters. /// </summary> public bool ShowBoxForControlCharacters { get; set; } /// <summary> /// Creates a new SingleCharacterElementGenerator instance. /// </summary> public SingleCharacterElementGenerator() { ShowSpaces = true; ShowTabs = true; ShowBoxForControlCharacters = true; } void IBuiltinElementGenerator.FetchOptions(TextEditorOptions options) { ShowSpaces = options.ShowSpaces; ShowTabs = options.ShowTabs; ShowBoxForControlCharacters = options.ShowBoxForControlCharacters; } public override int GetFirstInterestedOffset(int startOffset) { var endLine = CurrentContext.VisualLine.LastDocumentLine; var relevantText = CurrentContext.GetText(startOffset, endLine.EndOffset - startOffset); for (var i = 0; i < relevantText.Count; i++) { var c = relevantText.Text[relevantText.Offset + i]; switch (c) { case ' ': if (ShowSpaces) return startOffset + i; break; case '\t': if (ShowTabs) return startOffset + i; break; default: if (ShowBoxForControlCharacters && char.IsControl(c)) { return startOffset + i; } break; } } return -1; } public override VisualLineElement ConstructElement(int offset) { var c = CurrentContext.Document.GetCharAt(offset); if (ShowSpaces && c == ' ') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new SpaceTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowSpacesGlyph, runProperties)); } else if (ShowTabs && c == '\t') { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(CurrentContext.TextView.NonPrintableCharacterBrush); return new TabTextElement(CurrentContext.TextView.CachedElements.GetTextForNonPrintableCharacter( CurrentContext.TextView.Options.ShowTabsGlyph, runProperties)); } else if (ShowBoxForControlCharacters && char.IsControl(c)) { var runProperties = new VisualLineElementTextRunProperties(CurrentContext.GlobalTextRunProperties); runProperties.SetForegroundBrush(Brushes.White); var textFormatter = TextFormatterFactory.Create(CurrentContext.TextView); var text = FormattedTextElement.PrepareText(textFormatter, TextUtilities.GetControlCharacterName(c), runProperties); return new SpecialCharacterBoxElement(text); } return null; } private sealed class SpaceTextElement : FormattedTextElement { public SpaceTextElement(TextLine textLine) : base(textLine, 1) { } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabTextElement : VisualLineElement { internal readonly TextLine Text; public TabTextElement(TextLine text) : base(2, 1) { Text = text; } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { // the TabTextElement consists of two TextRuns: // first a TabGlyphRun, then TextCharacters '\t' to let WPF handle the tab indentation if (startVisualColumn == VisualColumn) return new TabGlyphRun(this, TextRunProperties); else if (startVisualColumn == VisualColumn + 1) return new TextCharacters(new ReadOnlySlice<char>("\t".AsMemory(), VisualColumn + 1, 1), TextRunProperties); else throw new ArgumentOutOfRangeException(nameof(startVisualColumn)); } public override int GetNextCaretPosition(int visualColumn, LogicalDirection direction, CaretPositioningMode mode) { if (mode == CaretPositioningMode.Normal || mode == CaretPositioningMode.EveryCodepoint) return base.GetNextCaretPosition(visualColumn, direction, mode); else return -1; } public override bool IsWhitespace(int visualColumn) { return true; } } private sealed class TabGlyphRun : DrawableTextRun { private readonly TabTextElement _element; public TabGlyphRun(TabTextElement element, TextRunProperties properties) { public override Size GetSize(double remainingParagraphWidth) { return new Size( _element.Text.WidthIncludingTrailingWhitespace, _element.Text.Height); } public override Rect ComputeBoundingBox() public override double Baseline => _element.Text.Baseline; public override Size Size => Size.Empty; public override void Draw(DrawingContext drawingContext, Point origin) { _element.Text.Draw(drawingContext, origin); } } private sealed class SpecialCharacterBoxElement : FormattedTextElement { public SpecialCharacterBoxElement(TextLine text) : base(text, 1) { } public override TextRun CreateTextRun(int startVisualColumn, ITextRunConstructionContext context) { return new SpecialCharacterTextRun(this, TextRunProperties); } } internal sealed class SpecialCharacterTextRun : FormattedTextRun { private static readonly ISolidColorBrush DarkGrayBrush; internal const double BoxMargin = 3; static SpecialCharacterTextRun() { DarkGrayBrush = new ImmutableSolidColorBrush(Color.FromArgb(200, 128, 128, 128)); } public SpecialCharacterTextRun(FormattedTextElement element, TextRunProperties properties) : base(element, properties) { } public override Size Size { get { var s = base.Size; return s.WithWidth(s.Width + BoxMargin); } } public override void Draw(DrawingContext drawingContext, Point origin) { var (x, y) = origin; var newOrigin = new Point(x + (BoxMargin / 2), y); var (width, height) = Size; var r = new Rect(x, y, width, height); drawingContext.FillRectangle(DarkGrayBrush, r, 2.5f); base.Draw(drawingContext, newOrigin); } } } } <MSG> Merge branch 'master' into dev <DFF> @@ -195,9 +195,7 @@ namespace AvaloniaEdit.Rendering public override Size GetSize(double remainingParagraphWidth) { - return new Size( - _element.Text.WidthIncludingTrailingWhitespace, - _element.Text.Height); + return new Size(0, _element.Text.Height); } public override Rect ComputeBoundingBox()
1
Merge branch 'master' into dev
3
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066502
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066503
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066504
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066505
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066506
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066507
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066508
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066509
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066510
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066511
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066512
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066513
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066514
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066515
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066516
<NME> AvaloniaEditCommands.cs <BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System.Diagnostics.CodeAnalysis; using Avalonia; using Avalonia.Input; using Avalonia.Platform; namespace AvaloniaEdit { /// <summary> /// Custom commands for AvalonEdit. /// </summary> public static class AvaloniaEditCommands { /// <summary> /// Toggles Overstrike mode /// The default shortcut is Ins. /// </summary> public static RoutedCommand ToggleOverstrike { get; } = new RoutedCommand(nameof(ToggleOverstrike), new KeyGesture(Key.Insert)); /// <summary> /// Deletes the current line. /// The default shortcut is Ctrl+D. /// </summary> public static RoutedCommand DeleteLine { get; } = new RoutedCommand(nameof(DeleteLine), new KeyGesture(Key.D, KeyModifiers.Control)); /// <summary> /// Removes leading whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveLeadingWhitespace { get; } = new RoutedCommand(nameof(RemoveLeadingWhitespace)); /// <summary> /// Removes trailing whitespace from the selected lines (or the whole document if the selection is empty). /// </summary> [SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", MessageId = "Whitespace")] public static RoutedCommand RemoveTrailingWhitespace { get; } = new RoutedCommand(nameof(RemoveTrailingWhitespace)); /// <summary> /// Converts the selected text to upper case. /// </summary> public static RoutedCommand ConvertToUppercase { get; } = new RoutedCommand(nameof(ConvertToUppercase)); /// <summary> /// Converts the selected text to lower case. /// </summary> public static RoutedCommand ConvertToLowercase { get; } = new RoutedCommand(nameof(ConvertToLowercase)); /// <summary> /// Converts the selected text to title case. /// </summary> public static RoutedCommand ConvertToTitleCase { get; } = new RoutedCommand(nameof(ConvertToTitleCase)); /// <summary> /// Inverts the case of the selected text. /// </summary> public static RoutedCommand InvertCase { get; } = new RoutedCommand(nameof(InvertCase)); /// <summary> /// Converts tabs to spaces in the selected text. /// </summary> public static RoutedCommand ConvertTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertTabsToSpaces)); /// <summary> /// Converts spaces to tabs in the selected text. /// </summary> public static RoutedCommand ConvertSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertSpacesToTabs)); /// <summary> /// Converts leading tabs to spaces in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingTabsToSpaces { get; } = new RoutedCommand(nameof(ConvertLeadingTabsToSpaces)); /// <summary> /// Converts leading spaces to tabs in the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand ConvertLeadingSpacesToTabs { get; } = new RoutedCommand(nameof(ConvertLeadingSpacesToTabs)); /// <summary>InputModifiers /// Runs the IIndentationStrategy on the selected lines (or the whole document if the selection is empty). /// </summary> public static RoutedCommand IndentSelection { get; } = new RoutedCommand(nameof(IndentSelection), new KeyGesture(Key.I, KeyModifiers.Control)); } public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() { return AvaloniaLocator.Current.GetService<IRuntimePlatform>().GetRuntimeInfo().OperatingSystem; } private static KeyModifiers GetPlatformCommandKey() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return KeyModifiers.Meta; } return KeyModifiers.Control; } private static KeyGesture GetReplaceKeyGesture() { var os = GetOperatingSystemType(); if (os == OperatingSystemType.OSX) { return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; } return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; } } public static class EditingCommands { public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete)); public static RoutedCommand DeleteNextWord { get; } = new RoutedCommand(nameof(DeleteNextWord)); public static RoutedCommand Backspace { get; } = new RoutedCommand(nameof(Backspace)); public static RoutedCommand DeletePreviousWord { get; } = new RoutedCommand(nameof(DeletePreviousWord)); public static RoutedCommand EnterParagraphBreak { get; } = new RoutedCommand(nameof(EnterParagraphBreak)); public static RoutedCommand EnterLineBreak { get; } = new RoutedCommand(nameof(EnterLineBreak)); public static RoutedCommand TabForward { get; } = new RoutedCommand(nameof(TabForward)); public static RoutedCommand TabBackward { get; } = new RoutedCommand(nameof(TabBackward)); public static RoutedCommand MoveLeftByCharacter { get; } = new RoutedCommand(nameof(MoveLeftByCharacter)); public static RoutedCommand SelectLeftByCharacter { get; } = new RoutedCommand(nameof(SelectLeftByCharacter)); public static RoutedCommand MoveRightByCharacter { get; } = new RoutedCommand(nameof(MoveRightByCharacter)); public static RoutedCommand SelectRightByCharacter { get; } = new RoutedCommand(nameof(SelectRightByCharacter)); public static RoutedCommand MoveLeftByWord { get; } = new RoutedCommand(nameof(MoveLeftByWord)); public static RoutedCommand SelectLeftByWord { get; } = new RoutedCommand(nameof(SelectLeftByWord)); public static RoutedCommand MoveRightByWord { get; } = new RoutedCommand(nameof(MoveRightByWord)); public static RoutedCommand SelectRightByWord { get; } = new RoutedCommand(nameof(SelectRightByWord)); public static RoutedCommand MoveUpByLine { get; } = new RoutedCommand(nameof(MoveUpByLine)); public static RoutedCommand SelectUpByLine { get; } = new RoutedCommand(nameof(SelectUpByLine)); public static RoutedCommand MoveDownByLine { get; } = new RoutedCommand(nameof(MoveDownByLine)); public static RoutedCommand SelectDownByLine { get; } = new RoutedCommand(nameof(SelectDownByLine)); public static RoutedCommand MoveDownByPage { get; } = new RoutedCommand(nameof(MoveDownByPage)); public static RoutedCommand SelectDownByPage { get; } = new RoutedCommand(nameof(SelectDownByPage)); public static RoutedCommand MoveUpByPage { get; } = new RoutedCommand(nameof(MoveUpByPage)); public static RoutedCommand SelectUpByPage { get; } = new RoutedCommand(nameof(SelectUpByPage)); public static RoutedCommand MoveToLineStart { get; } = new RoutedCommand(nameof(MoveToLineStart)); public static RoutedCommand SelectToLineStart { get; } = new RoutedCommand(nameof(SelectToLineStart)); public static RoutedCommand MoveToLineEnd { get; } = new RoutedCommand(nameof(MoveToLineEnd)); public static RoutedCommand SelectToLineEnd { get; } = new RoutedCommand(nameof(SelectToLineEnd)); public static RoutedCommand MoveToDocumentStart { get; } = new RoutedCommand(nameof(MoveToDocumentStart)); public static RoutedCommand SelectToDocumentStart { get; } = new RoutedCommand(nameof(SelectToDocumentStart)); public static RoutedCommand MoveToDocumentEnd { get; } = new RoutedCommand(nameof(MoveToDocumentEnd)); public static RoutedCommand SelectToDocumentEnd { get; } = new RoutedCommand(nameof(SelectToDocumentEnd)); } } <MSG> Update avalonia + fix keymodifiers <DFF> @@ -102,15 +102,15 @@ namespace AvaloniaEdit public static class ApplicationCommands { private static readonly KeyModifiers PlatformCommandKey = GetPlatformCommandKey(); - - public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture { Key = Key.Delete }); - public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.C }); - public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.X }); - public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.V }); - public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.A }); - public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Z }); - public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.Y }); - public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.F }); + + public static RoutedCommand Delete { get; } = new RoutedCommand(nameof(Delete), new KeyGesture(Key.Delete)); + public static RoutedCommand Copy { get; } = new RoutedCommand(nameof(Copy), new KeyGesture(Key.C, KeyModifiers.Control)); + public static RoutedCommand Cut { get; } = new RoutedCommand(nameof(Cut), new KeyGesture(Key.X, KeyModifiers.Control)); + public static RoutedCommand Paste { get; } = new RoutedCommand(nameof(Paste), new KeyGesture(Key.V, KeyModifiers.Control)); + public static RoutedCommand SelectAll { get; } = new RoutedCommand(nameof(SelectAll), new KeyGesture(Key.A, PlatformCommandKey)); + public static RoutedCommand Undo { get; } = new RoutedCommand(nameof(Undo), new KeyGesture(Key.Z, KeyModifiers.Control)); + public static RoutedCommand Redo { get; } = new RoutedCommand(nameof(Redo), new KeyGesture(Key.Y, KeyModifiers.Control)); + public static RoutedCommand Find { get; } = new RoutedCommand(nameof(Find), new KeyGesture(Key.F, KeyModifiers.Control)); public static RoutedCommand Replace { get; } = new RoutedCommand(nameof(Replace), GetReplaceKeyGesture()); private static OperatingSystemType GetOperatingSystemType() @@ -136,10 +136,10 @@ namespace AvaloniaEdit if (os == OperatingSystemType.OSX) { - return new KeyGesture { KeyModifiers = KeyModifiers.Meta | KeyModifiers.Alt, Key = Key.F }; + return new KeyGesture(Key.F, KeyModifiers.Meta | KeyModifiers.Alt); } - return new KeyGesture { KeyModifiers = PlatformCommandKey, Key = Key.H }; + return new KeyGesture(Key.H, PlatformCommandKey); } }
11
Update avalonia + fix keymodifiers
11
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10066517
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], deepEqual(loadedArgs.data, filteredData); }); test("search", function() { var $element = $("#jsGrid"), data = [ } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Add loading indicator support <DFF> @@ -253,6 +253,59 @@ $(function() { deepEqual(loadedArgs.data, filteredData); }); + asyncTest("loading indication", function() { + var timeout = 10, + stage = "initial", + $element = $("#jsGrid"), + + gridOptions = { + loadIndication: true, + loadIndicationDelay: timeout, + loadMessage: "loading...", + + loadIndicator: function(config) { + equal(config.message, gridOptions.loadMessage, "message provided"); + ok(config.container.jquery, "grid container is provided"); + + return { + show: function() { + stage = "started"; + }, + hide: function() { + stage = "finished"; + } + }; + }, + + fields: [ + { name: "field" } + ], + + controller: { + loadData: function() { + var deferred = $.Deferred(); + + equal(stage, "initial", "initial stage"); + + setTimeout(function() { + equal(stage, "started", "loading started"); + + deferred.resolve([]); + equal(stage, "finished", "loading finished"); + + start(); + }, timeout); + + return deferred.promise(); + } + } + }, + + grid = new Grid($element, gridOptions); + + grid.loadData(); + }); + test("search", function() { var $element = $("#jsGrid"), data = [
53
Core: Add loading indicator support
0
.js
tests
mit
tabalinas/jsgrid
10066518
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], deepEqual(loadedArgs.data, filteredData); }); test("search", function() { var $element = $("#jsGrid"), data = [ } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text").addClass("insert-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, gridOptions = { inserting: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", inserting: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); test("insert data with default location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Add loading indicator support <DFF> @@ -253,6 +253,59 @@ $(function() { deepEqual(loadedArgs.data, filteredData); }); + asyncTest("loading indication", function() { + var timeout = 10, + stage = "initial", + $element = $("#jsGrid"), + + gridOptions = { + loadIndication: true, + loadIndicationDelay: timeout, + loadMessage: "loading...", + + loadIndicator: function(config) { + equal(config.message, gridOptions.loadMessage, "message provided"); + ok(config.container.jquery, "grid container is provided"); + + return { + show: function() { + stage = "started"; + }, + hide: function() { + stage = "finished"; + } + }; + }, + + fields: [ + { name: "field" } + ], + + controller: { + loadData: function() { + var deferred = $.Deferred(); + + equal(stage, "initial", "initial stage"); + + setTimeout(function() { + equal(stage, "started", "loading started"); + + deferred.resolve([]); + equal(stage, "finished", "loading finished"); + + start(); + }, timeout); + + return deferred.promise(); + } + } + }, + + grid = new Grid($element, gridOptions); + + grid.loadData(); + }); + test("search", function() { var $element = $("#jsGrid"), data = [
53
Core: Add loading indicator support
0
.js
tests
mit
tabalinas/jsgrid
10066519
<NME> README.md <BEF> # Node-TimSort: Fast Sorting for Node.js [![Build Status](https://travis-ci.org/mziccard/node-timsort.svg?branch=master)](https://travis-ci.org/mziccard/node-timsort) [![npm version](https://badge.fury.io/js/timsort.svg)](https://www.npmjs.com/package/timsort) An adaptive and **stable** sort algorithm based on merging that requires fewer than nlog(n) comparisons when run on partially sorted arrays. The algorithm uses O(n) memory and still runs in O(nlogn) (worst case) on random arrays. This implementation is based on the original [TimSort](http://svn.python.org/projects/python/trunk/Objects/listsort.txt) developed by Tim Peters for Python's lists (code [here](http://svn.python.org/projects/python/trunk/Objects/listobject.c)). TimSort has been also adopted in Java starting from version 7. ## Acknowledgments - @novacrazy: ported the module to ES6/ES7 and made it available via bower - @kasperisager: implemented faster lexicographic comparison of small integers ## Usage Install the package with npm: ``` npm install --save timsort ``` And use it: ```javascript var TimSort = require('timsort'); var arr = [...]; TimSort.sort(arr); ``` You can also install it with bower: ``` bower install timsort ``` As `array.sort()` by default the `timsort` module sorts according to lexicographical order. You can also provide your own compare function (to sort any object) as: ```javascript function numberCompare(a,b) { return a-b; } var arr = [...]; var TimSort = require('timsort'); TimSort.sort(arr, numberCompare); ``` You can also sort only a specific subrange of the array: ```javascript TimSort.sort(arr, 5, 10); TimSort.sort(arr, numberCompare, 5, 10); ``` ## Performance A benchmark is provided in `benchmark/index.js`. It compares the `timsort` module against the default `array.sort` method in the numerical sorting of different types of integer array (as described [here](http://svn.python.org/projects/python/trunk/Objects/listsort.txt)): - *Random array* - *Descending array* - *Ascending array* - *Ascending array with 3 random exchanges* - *Ascending array with 10 random numbers in the end* - *Array of equal elements* - *Random Array with many duplicates* - *Random Array with some duplicates* For any of the array types the sorting is repeated several times and for different array sizes, average execution time is then printed. I run the benchmark on Node v6.3.1 (both pre-compiled and compiled from source, results are very similar), obtaining the following values: <table> <tr> <th></th><th></th> <th colspan="2">Execution Time (ns)</th> <th rowspan="2">Speedup</th> </tr> <tr> <th>Array Type</th> <th>Length</th> <th>TimSort.sort</th> <th>array.sort</th> </tr> <tbody> <tr> <td rowspan="4">Random</td><td>10</td><td>404</td><td>1583</td><td>3.91</td> </tr> <tr> <td>100</td><td>7147</td><td>4442</td><td>0.62</td> </tr> <tr> <td>1000</td><td>96395</td><td>59979</td><td>0.62</td> <td rowspan="4">Descending</td><td>10</td><td>642</td><td>2414</td><td>3.76</td> </tr> <tr> <td>100</td><td>1747</td><td>20710</td><td>11.85</td>/tr> <tr> <td>1000</td><td>8053</td><td>351682</td><td>43.67</td> </tr> <td>100</td><td>682</td><td>19210</td><td>28.14</td> </tr> <tr> <td>1000</td><td>3809</td><td>185185</td><td>48.61</td> </tr> <tr> <td>10000</td><td>35878</td><td>5392428</td><td>150.30</td> </tr> <tr> <td rowspan="4">Ascending</td><td>10</td><td>173</td><td>816</td><td>4.69</td> </tr> <tr> <td>100</td><td>578</td><td>18147</td><td>31.34</td> </tr> <tr> <td>1000</td><td>2551</td><td>331993</td><td>130.12</td> </tr> <tr> <td>10000</td><td>22098</td><td>5382446</td><td>243.57</td> </tr> <tr> <td rowspan="4">Ascending + 3 Rand Exc</td><td>10</td><td>232</td><td>927</td><td>3.99</td> </tr> <tr> <td>100</td><td>1059</td><td>15792</td><td>14.90</td> </tr> <tr> <td>1000</td><td>3525</td><td>300708</td><td>85.29</td> </tr> <tr> <td>10000</td><td>27455</td><td>4781370</td><td>174.15</td> </tr> <tr> <td rowspan="4">Ascending + 10 Rand End</td><td>10</td><td>378</td><td>1425</td><td>3.77</td> </tr> <tr> <td>100</td><td>1707</td><td>23346</td><td>13.67</td> </tr> <tr> <td>1000</td><td>5818</td><td>334744</td><td>57.53</td> </tr> <tr> <td>10000</td><td>38034</td><td>4985473</td><td>131.08</td> </tr> <tr> <td rowspan="4">Equal Elements</td><td>10</td><td>164</td><td>766</td><td>4.68</td> </tr> <tr> <td>100</td><td>520</td><td>3188</td><td>6.12</td> </tr> <tr> <td>1000</td><td>2340</td><td>27971</td><td>11.95</td> </tr> <tr> <td>10000</td><td>17011</td><td>281672</td><td>16.56</td> </tr> <tr> <td rowspan="4">Many Repetitions</td><td>10</td><td>396</td><td>1482</td><td>3.74</td> </tr> <tr> <td>100</td><td>7282</td><td>25267</td><td>3.47</td> </tr> <tr> <td>1000</td><td>105528</td><td>420120</td><td>3.98</td> </tr> <tr> <td>10000</td><td>1396120</td><td>5787399</td><td>4.15</td> </tr> <tr> <td rowspan="4">Some Repetitions</td><td>10</td><td>390</td><td>1463</td><td>3.75</td> </tr> <tr> <td>100</td><td>6678</td><td>20082</td><td>3.01</td> </tr> <tr> <td>1000</td><td>104344</td><td>374103</td><td>3.59</td> </tr> <tr> <td>10000</td><td>1333816</td><td>5474000</td><td>4.10</td> </tr> </tbody> </table> `TimSort.sort` **is faster** than `array.sort` on almost of the tested array types. In general, the more ordered the array is the better `TimSort.sort` performs with respect to `array.sort` (up to 243 times faster on already sorted arrays). And also, in general, the bigger the array the more we benefit from using the `timsort` module. These data strongly depend on Node.js version and the machine on which the benchmark is run. I strongly encourage you to run the benchmark on your own setup with: ``` npm run benchmark ``` Please also notice that: - This benchmark is far from exhaustive. Several cases are not considered and the results must be taken as partial - *inlining* is surely playing an active role in `timsort` module's good performance - A more accurate comparison of the algorithms would require implementing `array.sort` in pure javascript and counting element comparisons ## Stability TimSort is *stable* which means that equal items maintain their relative order after sorting. Stability is a desirable property for a sorting algorithm. Consider the following array of items with an height and a weight. ```javascript [ { height: 100, weight: 80 }, { height: 90, weight: 90 }, { height: 70, weight: 95 }, { height: 100, weight: 100 }, { height: 80, weight: 110 }, { height: 110, weight: 115 }, { height: 100, weight: 120 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 100, weight: 135 }, { height: 75, weight: 140 }, { height: 70, weight: 140 } ] ``` Items are already sorted by `weight`. Sorting the array according to the item's `height` with the `timsort` module results in the following array: ```javascript [ { height: 70, weight: 95 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 70, weight: 140 }, { height: 75, weight: 140 }, { height: 80, weight: 110 }, { height: 90, weight: 90 }, { height: 100, weight: 80 }, { height: 100, weight: 100 }, { height: 100, weight: 120 }, { height: 100, weight: 135 }, { height: 110, weight: 115 } ] ``` Items with the same `height` are still sorted by `weight` which means they preserved their relative order. `array.sort`, instead, is not guarranteed to be *stable*. In Node v0.12.7 sorting the previous array by `height` with `array.sort` results in: ```javascript [ { height: 70, weight: 140 }, { height: 70, weight: 95 }, { height: 70, weight: 125 }, { height: 70, weight: 130 }, { height: 75, weight: 140 }, { height: 80, weight: 110 }, { height: 90, weight: 90 }, { height: 100, weight: 100 }, { height: 100, weight: 80 }, { height: 100, weight: 135 }, { height: 100, weight: 120 }, { height: 110, weight: 115 } ] ``` As you can see the sorting did not preserve `weight` ordering for items with the same `height`. <MSG> Fixed readme table layout <DFF> @@ -95,7 +95,8 @@ results are very similar), obtaining the following values: <td rowspan="4">Descending</td><td>10</td><td>642</td><td>2414</td><td>3.76</td> </tr> <tr> - <td>100</td><td>1747</td><td>20710</td><td>11.85</td>/tr> + <td>100</td><td>1747</td><td>20710</td><td>11.85</td> +</tr> <tr> <td>1000</td><td>8053</td><td>351682</td><td>43.67</td> </tr>
2
Fixed readme table layout
1
.md
md
mit
mziccard/node-timsort
10066520
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066521
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066522
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066523
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066524
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066525
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066526
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066527
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066528
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066529
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066530
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066531
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066532
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066533
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066534
<NME> SR.Designer.cs <BEF> //------------------------------------------------------------------------------ // <auto-generated> // Dieser Code wurde von einem Tool generiert. // Laufzeitversion:4.0.30319.42000 // // Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn // der Code erneut generiert wird. // </auto-generated> //------------------------------------------------------------------------------ namespace AvaloniaEdit { using System; using System.Reflection; /// <summary> /// Eine stark typisierte Ressourcenklasse zum Suchen von lokalisierten Zeichenfolgen usw. /// </summary> // Diese Klasse wurde von der StronglyTypedResourceBuilder automatisch generiert // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class SR { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal SR() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Überschreibt die CurrentUICulture-Eigenschaft des aktuellen Threads für alle /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to Error: . /// </summary> internal static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> internal static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> internal static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match case. /// </summary> internal static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> internal static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> internal static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> internal static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> internal static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> internal static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> internal static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Toggle between find and replace modes ähnelt. /// </summary> public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } } /// <summary> /// Sucht eine lokalisierte Zeichenfolge, die Use regular expressions ähnelt. /// </summary> public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); } } } } <MSG> make embedded resource strings public. <DFF> @@ -10,7 +10,6 @@ namespace AvaloniaEdit { using System; - using System.Reflection; /// <summary> @@ -20,10 +19,10 @@ namespace AvaloniaEdit { // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. - [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] + [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "15.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] - internal class SR { + public class SR { private static global::System.Resources.ResourceManager resourceMan; @@ -37,10 +36,10 @@ namespace AvaloniaEdit { /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Resources.ResourceManager ResourceManager { + public static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { - global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).GetTypeInfo().Assembly); + global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("AvaloniaEdit.SR", typeof(SR).Assembly); resourceMan = temp; } return resourceMan; @@ -52,7 +51,7 @@ namespace AvaloniaEdit { /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] - internal static global::System.Globalization.CultureInfo Culture { + public static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } @@ -64,7 +63,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Error: . /// </summary> - internal static string SearchErrorText { + public static string SearchErrorText { get { return ResourceManager.GetString("SearchErrorText", resourceCulture); } @@ -73,7 +72,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find next (F3). /// </summary> - internal static string SearchFindNextText { + public static string SearchFindNextText { get { return ResourceManager.GetString("SearchFindNextText", resourceCulture); } @@ -82,7 +81,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Find previous (Shift+F3). /// </summary> - internal static string SearchFindPreviousText { + public static string SearchFindPreviousText { get { return ResourceManager.GetString("SearchFindPreviousText", resourceCulture); } @@ -91,7 +90,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match case. /// </summary> - internal static string SearchMatchCaseText { + public static string SearchMatchCaseText { get { return ResourceManager.GetString("SearchMatchCaseText", resourceCulture); } @@ -100,7 +99,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Match whole words. /// </summary> - internal static string SearchMatchWholeWordsText { + public static string SearchMatchWholeWordsText { get { return ResourceManager.GetString("SearchMatchWholeWordsText", resourceCulture); } @@ -109,7 +108,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to No matches found!. /// </summary> - internal static string SearchNoMatchesFoundText { + public static string SearchNoMatchesFoundText { get { return ResourceManager.GetString("SearchNoMatchesFoundText", resourceCulture); } @@ -118,7 +117,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace all (Alt+A). /// </summary> - internal static string SearchReplaceAll { + public static string SearchReplaceAll { get { return ResourceManager.GetString("SearchReplaceAll", resourceCulture); } @@ -127,7 +126,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Replace next (Alt+R). /// </summary> - internal static string SearchReplaceNext { + public static string SearchReplaceNext { get { return ResourceManager.GetString("SearchReplaceNext", resourceCulture); } @@ -136,7 +135,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Toggle between find and replace modes. /// </summary> - internal static string SearchToggleReplace { + public static string SearchToggleReplace { get { return ResourceManager.GetString("SearchToggleReplace", resourceCulture); } @@ -145,7 +144,7 @@ namespace AvaloniaEdit { /// <summary> /// Looks up a localized string similar to Use regular expressions. /// </summary> - internal static string SearchUseRegexText { + public static string SearchUseRegexText { get { return ResourceManager.GetString("SearchUseRegexText", resourceCulture); }
15
make embedded resource strings public.
16
.cs
Designer
mit
AvaloniaUI/AvaloniaEdit
10066535
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", var $element = $("#jsGrid"), updated = false, updatingArgs, updatedArgs, data = [{ field: "value" equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); } }, }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row.length, 1, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row.length, 1, "row element is provided in updated event args"); }); test("cancel edit", function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Provide updated row in onItemUpdated callback arguments fix Fixes #88 <DFF> @@ -1021,6 +1021,8 @@ $(function() { var $element = $("#jsGrid"), updated = false, updatingArgs, + updatingRow, + updatedRow, updatedArgs, data =
6
Core: Provide updated row in onItemUpdated callback arguments fix Fixes #88
2
.js
tests
mit
tabalinas/jsgrid
10066536
<NME> jsgrid.tests.js <BEF> $(function() { var Grid = jsGrid.Grid, JSGRID = "JSGrid", JSGRID_DATA_KEY = JSGRID; Grid.prototype.updateOnResize = false; module("basic"); test("default creation", function() { var gridOptions = { simpleOption: "test", complexOption: { a: "subtest", b: 1, c: {} } }, grid = new Grid("#jsGrid", gridOptions); equal(grid._container[0], $("#jsGrid")[0], "container saved"); equal(grid.simpleOption, "test", "primitive option extended"); equal(grid.complexOption, gridOptions.complexOption, "non-primitive option extended"); }); test("jquery adapter creation", function() { var gridOptions = { option: "test" }, $element = $("#jsGrid"), result = $element.jsGrid(gridOptions), grid = $element.data(JSGRID_DATA_KEY); equal(result, $element, "jquery fn returned source jQueryElement"); ok(grid instanceof Grid, "jsGrid saved to jquery data"); equal(grid.option, "test", "options provided"); }); test("destroy", function() { var $element = $("#jsGrid"), grid; $element.jsGrid({}); grid = $element.data(JSGRID_DATA_KEY); grid.destroy(); strictEqual($element.html(), "", "content is removed"); strictEqual($element.data(JSGRID_DATA_KEY), undefined, "jquery data is removed"); }); test("jquery adapter second call changes option value", function() { var $element = $("#jsGrid"), gridOptions = { option: "test" }, grid; $element.jsGrid(gridOptions); grid = $element.data(JSGRID_DATA_KEY); gridOptions.option = "new test"; $element.jsGrid(gridOptions); equal(grid, $element.data(JSGRID_DATA_KEY), "instance was not changed"); equal(grid.option, "new test", "option changed"); }); test("jquery adapter invokes jsGrid method", function() { var methodResult = "", $element = $("#jsGrid"), gridOptions = { method: function(str) { methodResult = "test_" + str; } }; $element.jsGrid(gridOptions); $element.jsGrid("method", "invoke"); equal(methodResult, "test_invoke", "method invoked"); }); test("onInit callback", function() { var $element = $("#jsGrid"), onInitArguments, gridOptions = { onInit: function(args) { onInitArguments = args; } }; var grid = new Grid($element, gridOptions); equal(onInitArguments.grid, grid, "grid instance is provided in onInit callback arguments"); }); test("controller methods are $.noop when not specified", function() { var $element = $("#jsGrid"), gridOptions = { controller: {} }, testOption; $element.jsGrid(gridOptions); deepEqual($element.data(JSGRID_DATA_KEY)._controller, { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, "controller has stub methods"); }); test("option method", function() { var $element = $("#jsGrid"), gridOptions = { test: "value" }, testOption; $element.jsGrid(gridOptions); testOption = $element.jsGrid("option", "test"); equal(testOption, "value", "read option value"); $element.jsGrid("option", "test", "new_value"); testOption = $element.jsGrid("option", "test"); equal(testOption, "new_value", "set option value"); }); test("fieldOption method", function() { var dataLoadedCount = 0; var $element = $("#jsGrid"), gridOptions = { loadMessage: "", autoload: true, controller: { loadData: function() { dataLoadedCount++; return [{ prop1: "value1", prop2: "value2", prop3: "value3" }]; } }, fields: [ { name: "prop1", title: "_" } ] }; $element.jsGrid(gridOptions); var fieldOptionValue = $element.jsGrid("fieldOption", "prop1", "name"); equal(fieldOptionValue, "prop1", "read field option"); $element.jsGrid("fieldOption", "prop1", "name", "prop2"); equal($element.text(), "_value2", "set field option by field name"); equal(dataLoadedCount, 1, "data not reloaded on field option change"); $element.jsGrid("fieldOption", 0, "name", "prop3"); equal($element.text(), "_value3", "set field option by field index"); }); test("option changing event handlers", function() { var $element = $("#jsGrid"), optionChangingEventArgs, optionChangedEventArgs, gridOptions = { test: "testValue", another: "anotherValue", onOptionChanging: function(e) { optionChangingEventArgs = $.extend({}, e); e.option = "another"; e.newValue = e.newValue + "_" + this.another; }, onOptionChanged: function(e) { optionChangedEventArgs = $.extend({}, e); } }, anotherOption; $element.jsGrid(gridOptions); $element.jsGrid("option", "test", "newTestValue"); equal(optionChangingEventArgs.option, "test", "option name is provided in args of optionChanging"); equal(optionChangingEventArgs.oldValue, "testValue", "old option value is provided in args of optionChanging"); equal(optionChangingEventArgs.newValue, "newTestValue", "new option value is provided in args of optionChanging"); anotherOption = $element.jsGrid("option", "another"); equal(anotherOption, "newTestValue_anotherValue", "option changing handler changed option and value"); equal(optionChangedEventArgs.option, "another", "option name is provided in args of optionChanged"); equal(optionChangedEventArgs.value, "newTestValue_anotherValue", "option value is provided in args of optionChanged"); }); test("common layout rendering", function() { var $element = $("#jsGrid"), grid = new Grid($element, {}), $headerGrid, $headerGridTable, $bodyGrid, $bodyGridTable; ok($element.hasClass(grid.containerClass), "container class attached"); ok($element.children().eq(0).hasClass(grid.gridHeaderClass), "grid header"); ok($element.children().eq(1).hasClass(grid.gridBodyClass), "grid body"); ok($element.children().eq(2).hasClass(grid.pagerContainerClass), "pager container"); $headerGrid = $element.children().eq(0); $headerGridTable = $headerGrid.children().first(); ok($headerGridTable.hasClass(grid.tableClass), "header table"); equal($headerGrid.find("." + grid.headerRowClass).length, 1, "header row"); equal($headerGrid.find("." + grid.filterRowClass).length, 1, "filter row"); equal($headerGrid.find("." + grid.insertRowClass).length, 1, "insert row"); ok(grid._headerRow.hasClass(grid.headerRowClass), "header row class"); ok(grid._filterRow.hasClass(grid.filterRowClass), "filter row class"); ok(grid._insertRow.hasClass(grid.insertRowClass), "insert row class"); $bodyGrid = $element.children().eq(1); $bodyGridTable = $bodyGrid.children().first(); ok($bodyGridTable.hasClass(grid.tableClass), "body table"); equal(grid._content.parent()[0], $bodyGridTable[0], "content is tbody in body table"); equal($bodyGridTable.find("." + grid.noDataRowClass).length, 1, "no data row"); equal($bodyGridTable.text(), grid.noDataContent, "no data text"); }); test("set default options with setDefaults", function() { jsGrid.setDefaults({ defaultOption: "test" }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "defaultOption"), "test", "default option set"); }); module("loading"); test("loading with controller", function() { var $element = $("#jsGrid"), data = [ { test: "test1" }, { test: "test2" } ], gridOptions = { controller: { loadData: function() { return data; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data"), data, "loadData loads data"); }); test("loadData throws exception when controller method not found", function() { var $element = $("#jsGrid"); var grid = new Grid($element); grid._controller = {}; throws(function() { grid.loadData(); }, /loadData/, "loadData threw an exception"); }); test("onError event should be fired on controller fail", function() { var errorArgs, errorFired = 0, $element = $("#jsGrid"), gridOptions = { controller: { loadData: function() { return $.Deferred().reject({ value: 1 }, "test").promise(); } }, onError: function(args) { errorFired++; errorArgs = args; } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(errorFired, 1, "onError handler fired"); deepEqual(errorArgs, { grid: grid, args: [{ value: 1 }, "test"] }, "error has correct params"); }); asyncTest("autoload should call loadData after render", 1, function() { new Grid($("#jsGrid"), { autoload: true, controller: { loadData: function() { ok(true, "autoload calls loadData on creation"); start(); return []; } } }); }); test("loading filtered data", function() { var filteredData, loadingArgs, loadedArgs, $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], onDataLoading: function(e) { loadingArgs = $.extend(true, {}, e); }, onDataLoaded: function(e) { loadedArgs = $.extend(true, {}, e); }, controller: { loadData: function(filter) { filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.loadData(); equal(loadingArgs.filter.field, "test"); equal(grid.option("data").length, 2, "filtered data loaded"); deepEqual(loadedArgs.data, filteredData); }); asyncTest("loading indication", function() { var timeout = 10, stage = "initial", $element = $("#jsGrid"), gridOptions = { loadIndication: true, loadIndicationDelay: timeout, loadMessage: "loading...", loadIndicator: function(config) { equal(config.message, gridOptions.loadMessage, "message provided"); ok(config.container.jquery, "grid container is provided"); return { show: function() { stage = "started"; }, hide: function() { stage = "finished"; } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); equal(stage, "initial", "initial stage"); setTimeout(function() { equal(stage, "started", "loading started"); deferred.resolve([]); equal(stage, "finished", "loading finished"); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); asyncTest("loadingIndication=false should not show loading", 0, function() { var $element = $("#jsGrid"), timeout = 10, gridOptions = { loadIndication: false, loadIndicationDelay: timeout, loadIndicator: function() { return { show: function() { ok(false, "should not call show"); }, hide: function() { ok(false, "should not call hide"); } }; }, fields: [ { name: "field" } ], controller: { loadData: function() { var deferred = $.Deferred(); setTimeout(function() { deferred.resolve([]); start(); }, timeout); return deferred.promise(); } } }, grid = new Grid($element, gridOptions); grid.loadData(); }); test("search", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { pageIndex: 2, _sortField: "field", _sortOrder: "desc", filtering: true, fields: [ { name: "field", filterValue: function(value) { return "test"; } } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search(); equal(grid.option("data").length, 2, "data filtered"); strictEqual(grid.option("pageIndex"), 1, "pageIndex reset"); strictEqual(grid._sortField, null, "sortField reset"); strictEqual(grid._sortOrder, "asc", "sortOrder reset"); }); test("change loadStrategy on the fly", function() { var $element = $("#jsGrid"); var gridOptions = { controller: { loadData: function() { return []; } } }; var grid = new Grid($element, gridOptions); grid.option("loadStrategy", { firstDisplayIndex: function() { return 0; }, lastDisplayIndex: function() { return 1; }, loadParams: function() { return []; }, finishLoad: function() { grid.option("data", [{}]); } }); grid.loadData(); equal(grid.option("data").length, 1, "new load strategy is applied"); }); module("filtering"); test("filter rendering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { name: "test", align: "right", filtercss: "filter-class", filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text").addClass("filter-input"); return result; } } ] }, grid = new Grid($element, gridOptions); equal(grid._filterRow.find(".filter-class").length, 1, "filtercss class is attached"); equal(grid._filterRow.find(".filter-input").length, 1, "filter control rendered"); equal(grid._filterRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._filterRow.find(".filter-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].filterControl.is("input[type=text]"), "filter control saved in field"); }); test("filter get/clear", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, controller: { loadData: function() { return []; } }, fields: [ { name: "field", filterTemplate: function() { return this.filterControl = $("<input>").attr("type", "text"); }, filterValue: function() { return this.filterControl.val(); } } ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); deepEqual(grid.getFilter(), { field: "test" }, "get filter"); grid.clearFilter(); deepEqual(grid.getFilter(), { field: "" }, "filter cleared"); equal(grid.fields[0].filterControl.val(), "", "grid field filterControl cleared"); }); test("field without filtering", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { filterTemplate: function() { var result = this.filterControl = $("<input>").attr("type", "text"); return result; }, filterValue: function(value) { if(!arguments.length) { return this.filterControl.val(); } this.filterControl.val(value); } }, gridOptions = { filtering: true, fields: [ $.extend({}, jsGridFieldConfig, { name: "field1", filtering: false }), $.extend({}, jsGridFieldConfig, { name: "field2" }) ] }, grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test1"); grid.fields[1].filterControl.val("test2"); deepEqual(grid.getFilter(), { field2: "test2" }, "field with filtering=false is not included in filter"); }); test("search with filter", function() { var $element = $("#jsGrid"), data = [ { field: "test" }, { field: "test_another" }, { field: "test_another" }, { field: "test" } ], gridOptions = { fields: [ { name: "field" } ], controller: { loadData: function(filter) { var filteredData = $.grep(data, function(item) { return item.field === filter.field; }); return filteredData; } } }, grid = new Grid($element, gridOptions); grid.search({ field: "test" }); equal(grid.option("data").length, 2, "data filtered"); }); test("filtering with static data should not do actual filtering", function() { var $element = $("#jsGrid"), gridOptions = { filtering: true, fields: [ { type: "text", name: "field" } ], data: [ { name: "value1" }, { name: "value2" } ] }, grid = new Grid($element, gridOptions); grid._filterRow.find("input").val("1"); grid.search(); equal(grid.option("data").length, 2, "data is not filtered"); }); module("nodatarow"); test("nodatarow after bind on empty array", function() { var $element = $("#jsGrid"), gridOptions = {}, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.noDataRowClass).length, 1, "no data row rendered"); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), grid.noDataContent, "no data text rendered"); }); test("nodatarow customize content", function() { var noDataMessage = "NoData Custom Content", $element = $("#jsGrid"), gridOptions = { noDataContent: function() { return noDataMessage; } }, grid = new Grid($element, gridOptions); grid.option("data", []); equal(grid._content.find("." + grid.cellClass).length, 1, "grid cell class attached"); equal(grid._content.text(), noDataMessage, "custom noDataContent"); }); module("row rendering", { setup: function() { this.testData = [ { id: 1, text: "test1" }, { id: 2, text: "test2" }, { id: 3, text: "test3" } ]; } }); test("rows rendered correctly", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData }, grid = new Grid($element, gridOptions); equal(grid._content.children().length, 3, "rows rendered"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "two odd rows for 3 items"); equal(grid._content.find("." + grid.evenRowClass).length, 1, "one even row for 3 items"); }); test("custom rowClass", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: "custom-row-cls" }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".custom-row-cls").length, 3, "custom row class"); }); test("custom rowClass callback", function() { var $element = $("#jsGrid"), gridOptions = { data: this.testData, rowClass: function(item, index) { return item.text; } }, grid = new Grid($element, gridOptions); equal(grid._content.find("." + grid.oddRowClass).length, 2); equal(grid._content.find("." + grid.evenRowClass).length, 1); equal(grid._content.find(".test1").length, 1, "custom row class"); equal(grid._content.find(".test2").length, 1, "custom row class"); equal(grid._content.find(".test3").length, 1, "custom row class"); }); test("rowClick standard handler", function() { var $element = $("#jsGrid"), $secondRow, grid = new Grid($element, { editing: true }); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); equal(grid._editingRow.get(0), $secondRow.get(0), "clicked row is editingRow"); }); test("rowClick handler", function() { var rowClickArgs, $element = $("#jsGrid"), $secondRow, gridOptions = { rowClick: function(args) { rowClickArgs = args; } }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("click", $.Event($secondRow)); ok(rowClickArgs.event instanceof jQuery.Event, "jquery event arg"); equal(rowClickArgs.item, this.testData[1], "item arg"); equal(rowClickArgs.itemIndex, 1, "itemIndex arg"); }); test("row selecting with selectedRowClass", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: true }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok($secondRow.hasClass(grid.selectedRowClass), "mouseenter adds selectedRowClass"); $secondRow.trigger("mouseleave", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseleave removes selectedRowClass"); }); test("no row selecting while selection is disabled", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { selecting: false }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); $secondRow = grid._content.find("." + grid.evenRowClass); $secondRow.trigger("mouseenter", $.Event($secondRow)); ok(!$secondRow.hasClass(grid.selectedRowClass), "mouseenter doesn't add selectedRowClass"); }); test("refreshing and refreshed callbacks", function() { var refreshingEventArgs, refreshedEventArgs, $element = $("#jsGrid"), grid = new Grid($element, {}); grid.onRefreshing = function(e) { refreshingEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 0, "no items before refresh"); }; grid.onRefreshed = function(e) { refreshedEventArgs = e; equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered after refresh"); }; grid.option("data", this.testData); equal(refreshingEventArgs.grid, grid, "grid provided in args for refreshing event"); equal(refreshedEventArgs.grid, grid, "grid provided in args for refreshed event"); equal(grid._content.find("." + grid.oddRowClass).length, 2, "items rendered"); }); test("grid fields normalization", function() { var CustomField = function(config) { $.extend(true, this, config); }; jsGrid.fields.custom = CustomField; try { var $element = $("#jsGrid"), gridOptions = { fields: [ new jsGrid.Field({ name: "text1", title: "title1" }), { name: "text2", title: "title2" }, { name: "text3", type: "custom" } ] }, grid = new Grid($element, gridOptions); var field1 = grid.fields[0]; ok(field1 instanceof jsGrid.Field); equal(field1.name, "text1", "name is set for field"); equal(field1.title, "title1", "title field"); var field2 = grid.fields[1]; ok(field2 instanceof jsGrid.Field); equal(field2.name, "text2", "name is set for field"); equal(field2.title, "title2", "title field"); var field3 = grid.fields[2]; ok(field3 instanceof CustomField); equal(field3.name, "text3", "name is set for field"); } finally { delete jsGrid.fields.custom; } }); test("'0' itemTemplate should be rendered", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}], fields: [ new jsGrid.Field({ name: "id", itemTemplate: function() { return 0; } }) ] }); equal(grid._bodyGrid.text(), "0", "item template is rendered"); }); test("grid field name used for header if title is not specified", function() { var $element = $("#jsGrid"), grid = new Grid($element, { fields: [ new jsGrid.Field({ name: "id" }) ] }); equal(grid._headerRow.text(), "id", "name is rendered in header"); }); test("grid fields header and item rendering", function() { var $element = $("#jsGrid"), $secondRow, gridOptions = { fields: [ new jsGrid.Field({ name: "text", title: "title", css: "cell-class", headercss: "header-class", align: "right" }) ] }, grid = new Grid($element, gridOptions); grid.option("data", this.testData); equal(grid._headerRow.text(), "title", "header rendered"); equal(grid._headerRow.find("." + grid.headerCellClass).length, 1, "header cell class is attached"); equal(grid._headerRow.find(".header-class").length, 1, "headercss class is attached"); ok(grid._headerRow.find(".header-class").hasClass("jsgrid-align-right"), "align class is attached"); $secondRow = grid._content.find("." + grid.evenRowClass); equal($secondRow.text(), "test2", "item rendered"); equal($secondRow.find(".cell-class").length, 1, "css class added to cell"); equal($secondRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($secondRow.find(".cell-class").hasClass("jsgrid-align-right"), "align class added to cell"); }); test("grid field cellRenderer", function() { var testItem = { text: "test" }, args; var $grid = $("#jsGrid"); var gridOptions = { data: [testItem], fields: [ { name: "text", cellRenderer: function(value, item) { args = { value: value, item: item }; return $("<td>").addClass("custom-class").text(value); } } ] }; var grid = new Grid($grid, gridOptions); var $customCell = $grid.find(".custom-class"); equal($customCell.length, 1, "custom cell rendered"); equal($customCell.text(), "test"); deepEqual(args, { value: "test", item: testItem }, "cellRenderer args provided"); }); test("grid field 'visible' option", function() { var $grid = $("#jsGrid"); var gridOptions = { editing: true, fields: [ { name: "id", visible: false }, { name: "test" } ] }; var grid = new Grid($grid, gridOptions); equal($grid.find("." + grid.noDataRowClass).children().eq(0).prop("colspan"), 1, "no data row colspan only for visible cells"); grid.option("data", this.testData); grid.editItem(this.testData[2]); equal($grid.find("." + grid.headerRowClass).children().length, 1, "header single cell"); equal($grid.find("." + grid.filterRowClass).children().length, 1, "filter single cell"); equal($grid.find("." + grid.insertRowClass).children().length, 1, "insert single cell"); equal($grid.find("." + grid.editRowClass).children().length, 1, "edit single cell"); equal($grid.find("." + grid.oddRowClass).eq(0).children().length, 1, "odd data row single cell"); equal($grid.find("." + grid.evenRowClass).eq(0).children().length, 1, "even data row single cell"); }); module("inserting"); test("inserting rendering", function() { var $element = $("#jsGrid"), gridOptions = { inserting: true, fields: [ { name: "test", align: "right", insertcss: "insert-class", var $element = $("#jsGrid"), updated = false, updatingArgs, updatedArgs, data = [{ field: "value" equal(grid._insertRow.find(".insert-class").length, 1, "insertcss class is attached"); equal(grid._insertRow.find(".insert-input").length, 1, "insert control rendered"); equal(grid._insertRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok(grid._insertRow.find(".insert-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].insertControl.is("input[type=text]"), "insert control saved in field"); }); test("field without inserting", function() { var $element = $("#jsGrid"), jsGridFieldConfig = { insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } }, }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); } }, }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test1"); grid.fields[1].insertControl.val("test2"); deepEqual(grid._getInsertItem(), { field2: "test2" }, "field with inserting=false is not included in inserting item"); }); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row.length, 1, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row.length, 1, "row element is provided in updated event args"); }); test("cancel edit", function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[1], { field: "test" }, "correct data is inserted"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insert data with specified insert location", function() { var $element = $("#jsGrid"), inserted = false, insertingArgs, insertedArgs, gridOptions = { inserting: true, insertRowLocation: "top", data: [{field: "default"}], fields: [ { name: "field", insertTemplate: function() { var result = this.insertControl = $("<input>").attr("type", "text"); return result; }, insertValue: function() { return this.insertControl.val(); } } ], onItemInserting: function(e) { insertingArgs = $.extend(true, {}, e); }, onItemInserted: function(e) { insertedArgs = $.extend(true, {}, e); }, controller: { insertItem: function() { inserted = true; } } }, grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(insertingArgs.item.field, "test", "field is provided in inserting args"); equal(grid.option("data").length, 2, "data is inserted"); ok(inserted, "controller insertItem was called"); deepEqual(grid.option("data")[0], { field: "test" }, "correct data is inserted at the beginning"); equal(insertedArgs.item.field, "test", "field is provided in inserted args"); }); test("insertItem accepts item to insert", function() { var $element = $("#jsGrid"), itemToInsert = { field: "test" }, insertedItem, gridOptions = { data: [], fields: [ { name: "field" } ], controller: { insertItem: function(item) { insertedItem = item; } } }, grid = new Grid($element, gridOptions); grid.insertItem(itemToInsert); deepEqual(grid.option("data")[0], itemToInsert, "data is inserted"); deepEqual(insertedItem, itemToInsert, "controller insertItem was called with correct item"); }); module("editing"); test("editing rendering", function() { var $element = $("#jsGrid"), $editRow, data = [{ test: "value" }], gridOptions = { editing: true, fields: [ { name: "test", align: "right", editcss: "edit-class", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value).addClass("edit-input"); return result; } } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); equal(grid._content.find("." + grid.editRowClass).length, 0, "no edit row after initial rendering"); grid.editItem(data[0]); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); equal($editRow.find(".edit-class").length, 1, "editcss class is attached"); equal($editRow.find(".edit-input").length, 1, "edit control rendered"); equal($editRow.find("." + grid.cellClass).length, 1, "cell class is attached"); ok($editRow.find(".edit-class").hasClass("jsgrid-align-right"), "align class is attached"); ok(grid.fields[0].editControl.is("input[type=text]"), "edit control saved in field"); equal(grid.fields[0].editControl.val(), "value", "edit control value"); }); test("editItem accepts row to edit", function() { var $element = $("#jsGrid"), $editRow, data = [ { test: "value" } ], gridOptions = { editing: true, fields: [ { name: "test" } ] }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.editItem($row); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); grid.cancelEdit(); grid.editItem($row.get(0)); $editRow = grid._content.find("." + grid.editRowClass); equal($editRow.length, 1, "edit row rendered"); }); test("edit item", function() { var $element = $("#jsGrid"), editingArgs, editingRow, updated = false, updatingArgs, updatingRow, updatedRow, updatedArgs, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { updated = true; } }, onItemEditing: function(e) { editingArgs = $.extend(true, {}, e); editingRow = grid.rowByItem(data[0])[0]; }, onItemUpdating: function(e) { updatingArgs = $.extend(true, {}, e); updatingRow = grid.rowByItem(data[0])[0]; }, onItemUpdated: function(e) { updatedArgs = $.extend(true, {}, e); updatedRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); deepEqual(editingArgs.item, { field: "value" }, "item before editing is provided in editing event args"); equal(editingArgs.itemIndex, 0, "itemIndex is provided in editing event args"); equal(editingArgs.row[0], editingRow, "row element is provided in editing event args"); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(updatingArgs.previousItem, { field: "value" }, "item before editing is provided in updating event args"); deepEqual(updatingArgs.item, { field: "new value" }, "updating item is provided in updating event args"); equal(updatingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(updatingArgs.row[0], updatingRow, "row element is provided in updating event args"); ok(updated, "controller updateItem called"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row rendered"); deepEqual(updatedArgs.previousItem, { field: "value" }, "item before editing is provided in updated event args"); deepEqual(updatedArgs.item, { field: "new value" }, "updated item is provided in updated event args"); equal(updatedArgs.itemIndex, 0, "itemIndex is provided in updated event args"); equal(updatedArgs.row[0], updatedRow, "row element is provided in updated event args"); }); test("failed update should not change original item", function() { var $element = $("#jsGrid"), data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateItem: function(updatingItem) { return $.Deferred().reject(); } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.updateItem(); deepEqual(grid.option("data")[0], { field: "value" }, "value is not updated"); }); test("cancel edit", function() { var $element = $("#jsGrid"), updated = false, cancellingArgs, cancellingRow, data = [{ field: "value" }], gridOptions = { editing: true, fields: [ { name: "field", editTemplate: function(value) { var result = this.editControl = $("<input>").attr("type", "text").val(value); return result; }, editValue: function() { return this.editControl.val(); } } ], controller: { updateData: function(updatingItem) { updated = true; } }, onItemEditCancelling: function(e) { cancellingArgs = $.extend(true, {}, e); cancellingRow = grid.rowByItem(data[0])[0]; } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.editItem(data[0]); grid.fields[0].editControl.val("new value"); grid.cancelEdit(); deepEqual(cancellingArgs.item, { field: "value" }, "item before cancel is provided in cancelling event args"); equal(cancellingArgs.itemIndex, 0, "itemIndex is provided in cancelling event args"); equal(cancellingArgs.row[0], cancellingRow, "row element is provided in cancelling event args"); ok(!updated, "controller updateItem was not called"); deepEqual(grid.option("data")[0], { field: "value" }, "data were not updated"); equal(grid._content.find("." + grid.editRowClass).length, 0, "edit row removed"); equal(grid._content.find("." + grid.oddRowClass).length, 1, "data row restored"); }); test("updateItem accepts item to update and new item", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.updateItem(data[0], { field: "new value" }); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("updateItem accepts single argument - item to update", function() { var $element = $("#jsGrid"), updatingItem, data = [{ field: "value" }], gridOptions = { fields: [ { name: "field" } ], controller: { updateItem: function(item) { return updatingItem = item; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); data[0].field = "new value"; grid.updateItem(data[0]); deepEqual(updatingItem, { field: "new value" }, "controller updateItem called correctly"); deepEqual(grid.option("data")[0], { field: "new value" }, "correct data updated"); }); test("editRowRenderer", function() { var $element = $("#jsGrid"), data = [ { value: "test" } ], gridOptions = { data: data, editing: true, editRowRenderer: function(item, itemIndex) { return $("<tr>").addClass("custom-edit-row").append($("<td>").text(itemIndex + ":" + item.value)); }, fields: [ { name: "value" } ] }, grid = new Grid($element, gridOptions); grid.editItem(data[0]); var $editRow = grid._content.find(".custom-edit-row"); equal($editRow.length, 1, "edit row rendered"); equal($editRow.text(), "0:test", "custom edit row renderer rendered"); }); module("deleting"); test("delete item", function() { var $element = $("#jsGrid"), deleted = false, deletingArgs, deletedArgs, data = [{ field: "value" }], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deleted = true; } }, onItemDeleting: function(e) { deletingArgs = $.extend(true, {}, e); }, onItemDeleted: function(e) { deletedArgs = $.extend(true, {}, e); } }, grid = new Grid($element, gridOptions); grid.option("data", data); grid.deleteItem(data[0]); deepEqual(deletingArgs.item, { field: "value" }, "field and value is provided in deleting event args"); equal(deletingArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletingArgs.row.length, 1, "row element is provided in updating event args"); ok(deleted, "controller deleteItem called"); equal(grid.option("data").length, 0, "data row deleted"); deepEqual(deletedArgs.item, { field: "value" }, "item is provided in updating event args"); equal(deletedArgs.itemIndex, 0, "itemIndex is provided in updating event args"); equal(deletedArgs.row.length, 1, "row element is provided in updating event args"); }); test("deleteItem accepts row", function() { var $element = $("#jsGrid"), deletedItem, itemToDelete = { field: "value" }, data = [itemToDelete], gridOptions = { confirmDeleting: false, fields: [ { name: "field" } ], controller: { deleteItem: function(deletingItem) { deletedItem = deletingItem; } } }, grid = new Grid($element, gridOptions); grid.option("data", data); var $row = $element.find("." + grid.oddRowClass).eq(0); grid.deleteItem($row); deepEqual(deletedItem, itemToDelete, "controller deleteItem called correctly"); equal(grid.option("data").length, 0, "data row deleted"); }); module("paging"); test("pager is rendered if necessary", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}], paging: false, pageSize: 2 }); ok(grid._pagerContainer.is(":hidden"), "pager is hidden when paging=false"); equal(grid._pagerContainer.html(), "", "pager is not rendered when paging=false"); grid.option("paging", true); ok(grid._pagerContainer.is(":visible"), "pager is visible when paging=true"); ok(grid._pagerContainer.html(), "pager is rendered when paging=true"); grid.option("data", [{}, {}]); ok(grid._pagerContainer.is(":hidden"), "pager is hidden for single page"); ok(grid._pagerContainer.html(), "pager is rendered for single page when paging=true"); }); test("external pagerContainer", function() { var $pagerContainer = $("<div>").appendTo("#qunit-fixture").hide(), $element = $("#jsGrid"); new Grid($element, { data: [{}, {}, {}], pagerContainer: $pagerContainer, paging: true, pageSize: 2 }); ok($pagerContainer.is(":visible"), "external pager shown"); ok($pagerContainer.html(), "external pager rendered"); }); test("pager functionality", function() { var $element = $("#jsGrid"), pager, pageChangedArgs, grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}, {}, {}, {}], onPageChanged: function(args) { pageChangedArgs = args; }, paging: true, pageSize: 2, pageButtonCount: 3 }); equal(grid._pagesCount(), 5, "correct page count"); equal(grid.option("pageIndex"), 1, "pageIndex is initialized"); equal(grid._firstDisplayingPage, 1, "_firstDisplayingPage is initialized"); pager = grid._pagerContainer; equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: Fisrt Prev Next Last ..."); equal(pager.find("." + grid.pagerNavButtonInactiveClass).length, 2, "two nav buttons inactive: Fisrt Prev"); grid.openPage(2); equal(pager.find("." + grid.currentPageClass).length, 1, "there is one current page"); ok(pager.find("." + grid.pageClass).eq(1).hasClass(grid.currentPageClass), "second page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); equal(pager.find("." + grid.pagerNavButtonClass).length, 5, "five nav buttons displayed: First Prev Next Last and ..."); equal(pageChangedArgs.pageIndex, 2, "onPageChanged callback provides pageIndex in arguments"); grid.showNextPages(); equal(grid._firstDisplayingPage, 3, "navigate by pages forward"); grid.showPrevPages(); equal(grid._firstDisplayingPage, 1, "navigate by pages backward"); grid.openPage(5); equal(grid._firstDisplayingPage, 3, "opening next non-visible page moves first displaying page forward"); grid.openPage(2); equal(grid._firstDisplayingPage, 2, "opening prev non-visible page moves first displaying page backward"); }); test("pager format", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}, {}, {}, {}, {}], paging: true, pageSize: 2, pageIndex: 2, pageButtonCount: 1, pagerFormat: "a {pageIndex} {first} {prev} {pages} {next} {last} {pageCount} {itemCount} z", pagePrevText: "<", pageNextText: ">", pageFirstText: "<<", pageLastText: ">>", pageNavigatorNextText: "np", pageNavigatorPrevText: "pp" }); grid._firstDisplayingPage = 2; grid._refreshPager(); equal($.trim(grid._pagerContainer.text()), "a 2 << < pp2np > >> 3 6 z", "pager text follows the format specified"); }); test("pagerRenderer", function() { var $element = $("#jsGrid"); var pagerRendererConfig; var pageSize = 2; var items = [{}, {}, {}, {}, {}, {}, {}]; var pageCount = Math.ceil(items.length / pageSize); var grid = new Grid($element, { data: items, paging: true, pageSize: pageSize, pagerRenderer: function(pagerConfig) { pagerRendererConfig = pagerConfig; } }); deepEqual(pagerRendererConfig, { pageIndex: 1, pageCount: pageCount }); grid.openPage(2); deepEqual(pagerRendererConfig, { pageIndex: 2, pageCount: pageCount }); }); test("loading by page", function() { var $element = $("#jsGrid"), data = [], itemCount = 20; for(var i = 1; i <= itemCount; i += 1) { data.push({ value: i }); } var gridOptions = { pageLoading: true, paging: true, pageSize: 7, fields: [ { name: "value" } ], controller: { loadData: function(filter) { var startIndex = (filter.pageIndex - 1) * filter.pageSize, result = data.slice(startIndex, startIndex + filter.pageSize); return { data: result, itemsCount: data.length }; } } }; var grid = new Grid($element, gridOptions); grid.loadData(); var pager = grid._pagerContainer; var gridData = grid.option("data"); equal(gridData.length, 7, "loaded one page of data"); equal(gridData[0].value, 1, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 7, "loaded correct data end value"); ok(pager.find("." + grid.pageClass).eq(0).hasClass(grid.currentPageClass), "first page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); grid.openPage(3); gridData = grid.option("data"); equal(gridData.length, 6, "loaded last page of data"); equal(gridData[0].value, 15, "loaded right data start value"); equal(gridData[gridData.length - 1].value, 20, "loaded right data end value"); ok(pager.find("." + grid.pageClass).eq(2).hasClass(grid.currentPageClass), "third page is current"); equal(pager.find("." + grid.pageClass).length, 3, "three pages displayed"); }); test("'openPage' method ignores indexes out of range", function() { var $element = $("#jsGrid"), grid = new Grid($element, { data: [{}, {}], paging: true, pageSize: 1 }); grid.openPage(0); equal(grid.option("pageIndex"), 1, "too small index is ignored"); grid.openPage(3); equal(grid.option("pageIndex"), 1, "too big index is ignored"); }); module("sorting"); test("sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); ok($th.hasClass(grid.sortableClass)); ok($th.hasClass(grid.sortAscClass)); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); ok(!$th.hasClass(grid.sortAscClass)); ok($th.hasClass(grid.sortDescClass)); }); test("sorting with pageLoading", function() { var $element = $("#jsGrid"), loadFilter, gridOptions = { sorting: true, pageLoading: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], controller: { loadData: function(filter) { loadFilter = filter; return { itemsCount: 0, data: [] }; } }, fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortOrder, "asc", "asc sorting order for first click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "asc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); $th.trigger("click"); equal(grid._sortOrder, "desc", "desc sorting order for second click"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(loadFilter.sortOrder, "desc", "sort direction is provided in loadFilter"); equal(loadFilter.sortField, "value", "sort field is provided in loadFilter"); }); test("no sorting for column with sorting = false", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorting: false } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal(grid._sortField, null, "sort field is not set for the field with sorting=false"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); equal($th.hasClass(grid.sortableClass), false, "no sorting css for field with sorting=false"); equal($th.hasClass(grid.sortAscClass), false, "no sorting css for field with sorting=false"); }); test("sort accepts sorting config", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); var gridData = grid.option("data"); grid.sort({ field: "value", order: "asc" }); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 1); equal(gridData[1].value, 2); equal(gridData[2].value, 3); grid.sort({ field: 0 }); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); equal(gridData[0].value, 3); equal(gridData[1].value, 2); equal(gridData[2].value, 1); grid.sort("value", "asc"); equal(grid._sortOrder, "asc", "asc sorting order is set"); equal(grid._sortField, grid.fields[0], "sort field is set"); grid.sort(0); equal(grid._sortOrder, "desc", "desc sorting order for already set asc sorting"); equal(grid._sortField, grid.fields[0], "sort field is set"); }); test("getSorting returns current sorting", function() { var $element = $("#jsGrid"), gridOptions = { sorting: true, data: [ { value: 3 }, { value: 2 }, { value: 1 } ], fields: [ { name: "value", sorter: "number" } ] }, grid = new Grid($element, gridOptions); deepEqual(grid.getSorting(), { field: undefined, order: undefined }, "undefined field and order before sorting"); grid.sort("value"); deepEqual(grid.getSorting(), { field: "value", order: "asc" }, "current sorting returned"); }); test("sorting css attached correctly when a field is hidden", function() { var $element = $("#jsGrid"); var gridOptions = { sorting: true, data: [], fields: [ { name: "field1", visible: false }, { name: "field2" } ] }; var grid = new Grid($element, gridOptions); var gridData = grid.option("data"); var $th = grid._headerRow.find("th").eq(0); $th.trigger("click"); equal($th.hasClass(grid.sortAscClass), true, "sorting css is attached to first field"); }); module("canceling events"); test("cancel item edit", function() { var $element = $("#jsGrid"); var data = [{}]; var gridOptions = { editing: true, onItemEditing: function(e) { e.cancel = true; }, controller: { loadData: function() { return data; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); grid.editItem(data[0]); strictEqual(grid._editingRow, null, "no editing row"); }); test("cancel controller.loadData", function() { var $element = $("#jsGrid"); var gridOptions = { onDataLoading: function(e) { e.cancel = true; }, controller: { loadData: function() { return [{}]; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.loadData(); equal(grid.option("data").length, 0, "no data loaded"); }); test("cancel controller.insertItem", function() { var $element = $("#jsGrid"); var insertedItem = null; var gridOptions = { onItemInserting: function(e) { e.cancel = true; }, controller: { insertItem: function(item) { insertedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.insertItem({ test: "value" }); strictEqual(insertedItem, null, "item was not inserted"); }); test("cancel controller.updateItem", function() { var $element = $("#jsGrid"); var updatedItem = null; var existingItem = { test: "value" }; var gridOptions = { data: [ existingItem ], onItemUpdating: function(e) { e.cancel = true; }, controller: { updateItem: function(item) { updatedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.updateItem(existingItem, { test: "new_value" }); strictEqual(updatedItem, null, "item was not updated"); }); test("cancel controller.deleteItem", function() { var $element = $("#jsGrid"); var deletingItem = { test: "value" }; var deletedItem = null; var gridOptions = { data: [ deletingItem ], confirmDeleting: false, onItemDeleting: function(e) { e.cancel = true; }, controller: { deleteItem: function(item) { deletedItem = item; } }, fields: [ { name: "test" } ] }; var grid = new Grid($element, gridOptions); grid.deleteItem(deletingItem); strictEqual(deletedItem, null, "item was not deleted"); }); module("complex properties binding"); test("rendering", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { prop: "test" } } ], fields: [ { name: "complexProp.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "test", "complex property value rendered"); }); test("editing", function() { var $element = $("#jsGrid"); var gridOptions = { editing: true, data: [ { complexProp: { prop: "test" } } ], fields: [ { type: "text", name: "complexProp.prop" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); equal(grid.fields[0].editControl.val(), "test", "complex property value set in editor"); }); test("should not fail if property is absent", function() { var $element = $("#jsGrid"); var gridOptions = { loadMessage: "", data: [ { complexProp: { } } ], fields: [ { name: "complexProp.subprop.prop", title: "" } ] }; new Grid($element, gridOptions); equal($element.text(), "", "rendered empty value"); }); test("inserting", function() { var $element = $("#jsGrid"); var insertingItem; var gridOptions = { inserting: true, fields: [ { type: "text", name: "complexProp.prop" } ], onItemInserting: function(args) { insertingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(insertingItem, { complexProp: { prop: "test" } }, "inserting item has complex properties"); }); test("filtering", function() { var $element = $("#jsGrid"); var loadFilter; var gridOptions = { filtering: true, fields: [ { type: "text", name: "complexProp.prop" } ], controller: { loadData: function(filter) { loadFilter = filter; } } }; var grid = new Grid($element, gridOptions); grid.fields[0].filterControl.val("test"); grid.search(); deepEqual(loadFilter, { complexProp: { prop: "test" } }, "filter has complex properties"); }); test("updating", function() { var $element = $("#jsGrid"); var updatingItem; var gridOptions = { editing: true, data: [ { complexProp: { } } ], fields: [ { type: "text", name: "complexProp.prop" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(updatingItem, { complexProp: { prop: "test" } }, "updating item has complex properties"); }); test("update nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { prop: { subprop1: "test1", subprop2: "test2" } } ], fields: [ { type: "text", name: "prop.subprop1" }, { type: "text", name: "prop.subprop2" } ], onItemUpdating: function(args) { updatingItem = args.item; } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("new_test1"); grid.updateItem(); var expectedUpdatingItem = { prop: { subprop1: "new_test1", subprop2: "test2" } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has nested properties"); }); test("updating deeply nested prop", function() { var $element = $("#jsGrid"); var updatingItem; var previousItem; var gridOptions = { editing: true, data: [ { complexProp: { subprop1: { another_prop: "test" } } } ], fields: [ { type: "text", name: "complexProp.subprop1.prop1" }, { type: "text", name: "complexProp.subprop1.subprop2.prop12" } ], onItemUpdating: function(args) { updatingItem = $.extend(true, {}, args.item); previousItem = $.extend(true, {}, args.previousItem); } }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test1"); grid.fields[1].editControl.val("test2"); grid.updateItem(); var expectedUpdatingItem = { complexProp: { subprop1: { another_prop: "test", prop1: "test1", subprop2: { prop12: "test2" } } } }; var expectedPreviousItem = { complexProp: { subprop1: { another_prop: "test" } } }; deepEqual(updatingItem, expectedUpdatingItem, "updating item has deeply nested properties"); deepEqual(previousItem, expectedPreviousItem, "previous item preserved correctly"); }); module("validation"); test("insertItem should call validation.validate", function() { var $element = $("#jsGrid"); var fieldValidationRules = { test: "value" }; var validatingArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return []; } }, fields: [ { type: "text", name: "Name", validate: fieldValidationRules } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: -1, row: grid._insertRow, rules: fieldValidationRules }, "validating args is provided"); }); test("insertItem rejected when data is not valid", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.fields[0].insertControl.val("test"); grid.insertItem().done(function() { ok(false, "insertItem should not be completed"); }).fail(function() { ok(true, "insertItem should fail"); }); }); test("invalidClass is attached on invalid cell on inserting", function() { var $element = $("#jsGrid"); var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Id", visible: false }, { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); var $insertCell = grid._insertRow.children().eq(0); grid.insertItem(); ok($insertCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($insertCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("onItemInvalid callback", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var onItemInvalidCalled = 0; var onItemInvalidArgs; var gridOptions = { data: [], inserting: true, invalidNotify: $.noop, onItemInvalid: function(args) { onItemInvalidCalled++; onItemInvalidArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid is called, when item data is invalid"); deepEqual(onItemInvalidArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], item: { Name: "" }, itemIndex: -1, row: grid._insertRow }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(onItemInvalidCalled, 1, "onItemInvalid was not called, when data is valid"); }); test("invalidNotify", function() { var $element = $("#jsGrid"); var errors = ["Error"]; var invalidNotifyCalled = 0; var invalidNotifyArgs; var gridOptions = { data: [], inserting: true, invalidNotify: function(args) { invalidNotifyCalled++; invalidNotifyArgs = args; }, validation: { validate: function(args) { return !args.value ? errors : []; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify is called, when item data is invalid"); deepEqual(invalidNotifyArgs, { grid: grid, errors: [{ field: grid.fields[0], message: "Error" }], row: grid._insertRow, item: { Name: "" }, itemIndex: -1 }, "arguments provided"); grid.fields[0].insertControl.val("test"); grid.insertItem(); equal(invalidNotifyCalled, 1, "invalidNotify was not called, when data is valid"); }); test("invalidMessage", function() { var $element = $("#jsGrid"); var invalidMessage; var originalAlert = window.alert; window.alert = function(message) { invalidMessage = message; }; try { Grid.prototype.invalidMessage = "InvalidTest"; Grid.prototype.invalidNotify({ errors: [{ message: "Message1" }, { message: "Message2" }] }); var expectedInvalidMessage = ["InvalidTest", "Message1", "Message2"].join("\n"); equal(invalidMessage, expectedInvalidMessage, "message contains invalidMessage and field error messages"); } finally { window.alert = originalAlert; } }); test("updateItem should call validation.validate", function() { var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: $.noop, validation: { validate: function(args) { validatingArgs = args; return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.fields[0].editControl.val("test"); grid.updateItem(); deepEqual(validatingArgs, { value: "test", item: { Name: "test" }, itemIndex: 0, row: grid._getEditRow(), rules: "required" }, "validating args is provided"); }); test("invalidClass is attached on invalid cell on updating", function() { var $element = $("#jsGrid"); var gridOptions = { data: [{}], editing: true, invalidNotify: $.noop, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", validate: true } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); var $editCell = grid._getEditRow().children().eq(0); grid.updateItem(); ok($editCell.hasClass(grid.invalidClass), "invalid class is attached"); equal($editCell.attr("title"), "Error", "cell tooltip contains error message"); }); test("validation should ignore not editable fields", function() { var invalidNotifyCalled = 0; var $element = $("#jsGrid"); var validatingArgs; var gridOptions = { data: [{ Name: "" }], editing: true, invalidNotify: function() { invalidNotifyCalled++; }, validation: { validate: function() { return ["Error"]; } }, fields: [ { type: "text", name: "Name", editing: false, validate: "required" } ] }; var grid = new Grid($element, gridOptions); grid.editItem(gridOptions.data[0]); grid.updateItem(); equal(invalidNotifyCalled, 0, "data is valid"); }); module("api"); test("reset method should go the first page when pageLoading is truned on", function() { var items = [{ Name: "1" }, { Name: "2" }]; var $element = $("#jsGrid"); var gridOptions = { paging: true, pageSize: 1, pageLoading: true, autoload: true, controller: { loadData: function(args) { return { data: [items[args.pageIndex - 1]], itemsCount: items.length }; } }, fields: [ { type: "text", name: "Name" } ] }; var grid = new Grid($element, gridOptions); grid.openPage(2); grid.reset(); equal(grid._bodyGrid.text(), "1", "grid content reset"); }); module("i18n"); test("set locale by name", function() { jsGrid.locales.my_lang = { grid: { test: "test_text" } }; jsGrid.locale("my_lang"); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("set locale by config", function() { jsGrid.locale( { grid: { test: "test_text" } }); var $element = $("#jsGrid").jsGrid({}); equal($element.jsGrid("option", "test"), "test_text", "option localized"); }); test("locale throws exception for unknown locale", function() { throws(function() { jsGrid.locale("unknown_lang"); }, /unknown_lang/, "locale threw an exception"); }); module("controller promise"); asyncTest("should support jQuery promise success callback", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.resolve(data); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support jQuery promise fail callback", 1, function() { var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { var d = $.Deferred(); setTimeout(function() { d.reject(failArgs); start(); }); return d.promise(); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); asyncTest("should support JS promise success callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { resolve(data); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); asyncTest("should support JS promise fail callback", 1, function() { if(typeof Promise === "undefined") { ok(true, "Promise not supported"); start(); return; } var failArgs = {}; var gridOptions = { autoload: false, controller: { loadData: function() { return new Promise(function(resolve, reject) { setTimeout(function() { reject(failArgs); start(); }); }); } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.fail(function(result) { equal(result, failArgs, "fail args provided to fail callback"); }); }); test("should support non-promise result", 1, function() { var data = []; var gridOptions = { autoload: false, controller: { loadData: function() { return data; } } }; var grid = new Grid($("#jsGrid"), gridOptions); var promise = grid._controllerCall("loadData", {}, false, $.noop); promise.done(function(result) { equal(result, data, "data provided to done callback"); }); }); module("renderTemplate"); test("should pass undefined and null arguments to the renderer", function() { var rendererArgs; var rendererContext; var context = {}; var renderer = function() { rendererArgs = arguments; rendererContext = this; }; Grid.prototype.renderTemplate(renderer, context, { arg1: undefined, arg2: null, arg3: "test" }); equal(rendererArgs.length, 3); strictEqual(rendererArgs[0], undefined, "undefined passed"); strictEqual(rendererArgs[1], null, "null passed"); strictEqual(rendererArgs[2], "test", "null passed"); strictEqual(rendererContext, context, "context is preserved"); }); module("Data Export", { setup: function() { this.exportConfig = {}; this.exportConfig.type = "csv"; this.exportConfig.subset = "all"; this.exportConfig.delimiter = "|"; this.exportConfig.includeHeaders = true; this.exportConfig.encapsulate = true; this.element = $("#jsGrid"); this.gridOptions = { width: "100%", height: "400px", inserting: true, editing: true, sorting: true, paging: true, pageSize: 2, data: [ { "Name": "Otto Clay", "Country": 1, "Married": false }, { "Name": "Connor Johnston", "Country": 2, "Married": true }, { "Name": "Lacey Hess", "Country": 2, "Married": false }, { "Name": "Timothy Henson", "Country": 1, "Married": true } ], fields: [ { name: "Name", type: "text", width: 150, validate: "required" }, { name: "Country", type: "select", items: [{ Name: "United States", Id: 1 },{ Name: "Canada", Id: 2 }], valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] } } }); /* Base Choice Criteria type: csv subset: all delimiter: | includeHeaders: true encapsulate: true */ test("Should export data: Base Choice",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV configured to Base Choice Criteria -- Check Source"); }); test("Should export data: defaults = BCC",function(){ var grid = new Grid($(this.element), this.gridOptions); var data = grid.exportData(); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV with all defaults -- Should be equal to Base Choice"); }); test("Should export data: subset=visible", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.subset = "visible"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV of visible records"); }); test("Should export data: delimiter=;", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.delimiter = ";"; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name";"Country";"Is Married"\r\n'; expected += '"Otto Clay";"United States";"false"\r\n'; expected += '"Connor Johnston";"Canada";"true"\r\n'; expected += '"Lacey Hess";"Canada";"false"\r\n'; expected += '"Timothy Henson";"United States";"true"\r\n'; equal(data, expected, "Output CSV with non-default delimiter"); }); test("Should export data: headers=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.includeHeaders = false; var data = grid.exportData(this.exportConfig); var expected = ""; //expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; expected += '"Connor Johnston"|"Canada"|"true"\r\n'; expected += '"Lacey Hess"|"Canada"|"false"\r\n'; expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV without Headers"); }); test("Should export data: encapsulate=false", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig.encapsulate = false; var data = grid.exportData(this.exportConfig); var expected = ""; expected += 'Name|Country|Is Married\r\n'; expected += 'Otto Clay|United States|false\r\n'; expected += 'Connor Johnston|Canada|true\r\n'; expected += 'Lacey Hess|Canada|false\r\n'; expected += 'Timothy Henson|United States|true\r\n'; equal(data, expected, "Output CSV without encapsulation"); }); test("Should export filtered data", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['filter'] = function(item){ if (item["Name"].indexOf("O") === 0) return true }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"false"\r\n'; //expected += '"Connor Johnston"|"Canada"|"true"\r\n'; //expected += '"Lacey Hess"|"Canada"|"false"\r\n'; //expected += '"Timothy Henson"|"United States"|"true"\r\n'; equal(data, expected, "Output CSV filtered to show names starting with O"); }); test("Should export data: transformed value", function(){ var grid = new Grid($(this.element), this.gridOptions); this.exportConfig['transforms'] = {}; this.exportConfig.transforms['Married'] = function(value){ if (value === true) return "Yes" if (value === false) return "No" }; var data = grid.exportData(this.exportConfig); var expected = ""; expected += '"Name"|"Country"|"Is Married"\r\n'; expected += '"Otto Clay"|"United States"|"No"\r\n'; expected += '"Connor Johnston"|"Canada"|"Yes"\r\n'; expected += '"Lacey Hess"|"Canada"|"No"\r\n'; expected += '"Timothy Henson"|"United States"|"Yes"\r\n'; equal(data, expected, "Output CSV column value transformed properly"); }); }); <MSG> Core: Provide updated row in onItemUpdated callback arguments fix Fixes #88 <DFF> @@ -1021,6 +1021,8 @@ $(function() { var $element = $("#jsGrid"), updated = false, updatingArgs, + updatingRow, + updatedRow, updatedArgs, data =
6
Core: Provide updated row in onItemUpdated callback arguments fix Fixes #88
2
.js
tests
mit
tabalinas/jsgrid
10066537
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066538
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066539
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066540
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066541
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066542
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066543
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066544
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066545
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066546
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066547
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066548
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10066549
<NME> TextEditorModel.cs <BEF> using System; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Model; namespace AvaloniaEdit.TextMate { public class TextEditorModel : AbstractLineList, IDisposable { private readonly TextDocument _document; private readonly TextView _textView; private DocumentSnapshot _documentSnapshot; private Action<Exception> _exceptionHandler; private InvalidLineRange _invalidRange; public DocumentSnapshot DocumentSnapshot { get { return _documentSnapshot; } } internal InvalidLineRange InvalidRange { get { return _invalidRange; } } public TextEditorModel(TextView textView, TextDocument document, Action<Exception> exceptionHandler) { _textView = textView; _document = document; _exceptionHandler = exceptionHandler; _documentSnapshot = new DocumentSnapshot(_document); for (int i = 0; i < _document.LineCount; i++) AddLine(i); _document.Changing += DocumentOnChanging; _document.Changed += DocumentOnChanged; _document.UpdateFinished += DocumentOnUpdateFinished; _textView.ScrollOffsetChanged += TextView_ScrollOffsetChanged; } public override void Dispose() { _document.Changing -= DocumentOnChanging; _document.Changed -= DocumentOnChanged; _document.UpdateFinished -= DocumentOnUpdateFinished; _textView.ScrollOffsetChanged -= TextView_ScrollOffsetChanged; } public override void UpdateLine(int lineIndex) { } public void InvalidateViewPortLines() { lock (_lock) { _lineRanges.Update(e); } } _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); } public override int GetNumberOfLines() { return _documentSnapshot.LineCount; } public override string GetLineText(int lineIndex) { return _documentSnapshot.GetLineText(lineIndex); } public override int GetLineLength(int lineIndex) { return _documentSnapshot.GetLineLength(lineIndex); } private void TextView_ScrollOffsetChanged(object sender, EventArgs e) { try { TokenizeViewPort(); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanging(object sender, DocumentChangeEventArgs e) { try { if (e.RemovalLength > 0) { var startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; var endLine = _document.GetLineByOffset(e.Offset + e.RemovalLength).LineNumber - 1; for (int i = endLine; i > startLine; i--) { RemoveLine(i); } _documentSnapshot.RemoveLines(startLine, endLine); } } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void DocumentOnChanged(object sender, DocumentChangeEventArgs e) { try { int startLine = _document.GetLineByOffset(e.Offset).LineNumber - 1; int endLine = startLine; if (e.InsertionLength > 0) { endLine = _document.GetLineByOffset(e.Offset + e.InsertionLength).LineNumber - 1; for (int i = startLine; i < endLine; i++) { AddLine(i); } } _documentSnapshot.Update(e); if (startLine == 0) { SetInvalidRange(startLine, endLine); return; } // some grammars (JSON, csharp, ...) // need to invalidate the previous line too SetInvalidRange(startLine - 1, endLine); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } private void SetInvalidRange(int startLine, int endLine) { if (!_document.IsInUpdate) { InvalidateLineRange(startLine, endLine); return; } // we're in a document change, store the max invalid range if (_invalidRange == null) { _invalidRange = new InvalidLineRange(startLine, endLine); return; } _invalidRange.SetInvalidRange(startLine, endLine); } void DocumentOnUpdateFinished(object sender, EventArgs e) { if (_invalidRange == null) return; try { InvalidateLineRange(_invalidRange.StartLine, _invalidRange.EndLine); } finally { _invalidRange = null; } } private void TokenizeViewPort() { Dispatcher.UIThread.InvokeAsync(() => { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; ForceTokenization( _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1, _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1); }, DispatcherPriority.MinValue); } internal class InvalidLineRange { internal int StartLine { get; private set; } internal int EndLine { get; private set; } internal InvalidLineRange(int startLine, int endLine) { StartLine = startLine; EndLine = endLine; } internal void SetInvalidRange(int startLine, int endLine) { if (startLine < StartLine) StartLine = startLine; if (endLine > EndLine) EndLine = endLine; } } } } <MSG> Also update _lineCount when updating the line ranges <DFF> @@ -51,6 +51,7 @@ namespace AvaloniaEdit.TextMate { lock (_lock) { + _lineCount = _document.LineCount; _lineRanges.Update(e); } }
1
Also update _lineCount when updating the line ranges
0
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit