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
10056750
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static void RegisterExceptionHandler(Action<Exception> handler) { _exceptionHandler = handler; } public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, IGrammar grammar = null) { return new Installation(editor, theme, grammar); } public class Installation { public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) { _textMateRegistryOptions = new RegistryOptions(defaultTheme); _textMateRegistry = new Registry(_textMateRegistryOptions); _editor = editor; SetTheme(defaultTheme); SetGrammar(grammar); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } public void SetGrammarByLanguageId(string languageId) { string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); } public void SetGrammar(IGrammar grammar) { _grammar = grammar; GetOrCreateTransformer().SetGrammar(grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(ThemeName themeName) { IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); _textMateRegistry.SetTheme(rawTheme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { _editor.DocumentChanged -= OnEditorOnDocumentChanged; DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); DisposeTransformer(_transformer); } void OnEditorOnDocumentChanged(object sender, EventArgs args) { try { DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); _editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); _transformer = GetOrCreateTransformer(); _transformer.SetModel(_editor.Document, _tmModel); _tmModel.AddModelTokensChangedListener(_transformer); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } tmModel.Dispose(); } RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel; if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) return; transformer.Dispose(); } static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer) { if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Refactor the TextMate class to receive an abstract IRegistryOptions <DFF> @@ -17,51 +17,38 @@ namespace AvaloniaEdit.TextMate public static Installation InstallTextMate( this TextEditor editor, - ThemeName theme, - IGrammar grammar = null) + IRegistryOptions registryOptions) { - return new Installation(editor, theme, grammar); + return new Installation(editor, registryOptions); } public class Installation { - public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } - - public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) + public Installation(TextEditor editor, IRegistryOptions registryOptions) { - _textMateRegistryOptions = new RegistryOptions(defaultTheme); - _textMateRegistry = new Registry(_textMateRegistryOptions); + _textMateRegistry = new Registry(registryOptions); _editor = editor; - SetTheme(defaultTheme); - SetGrammar(grammar); + SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } - public void SetGrammarByLanguageId(string languageId) + public void SetGrammar(string scopeName) { - string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); - SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); - } + _grammar = _textMateRegistry.LoadGrammar(scopeName); - public void SetGrammar(IGrammar grammar) - { - _grammar = grammar; - - GetOrCreateTransformer().SetGrammar(grammar); + GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } - public void SetTheme(ThemeName themeName) + public void SetTheme(IRawTheme theme) { - IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); - - _textMateRegistry.SetTheme(rawTheme); + _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); @@ -116,7 +103,6 @@ namespace AvaloniaEdit.TextMate tmModel.Dispose(); } - RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel;
10
Refactor the TextMate class to receive an abstract IRegistryOptions
24
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10056751
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static void RegisterExceptionHandler(Action<Exception> handler) { _exceptionHandler = handler; } public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, IGrammar grammar = null) { return new Installation(editor, theme, grammar); } public class Installation { public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) { _textMateRegistryOptions = new RegistryOptions(defaultTheme); _textMateRegistry = new Registry(_textMateRegistryOptions); _editor = editor; SetTheme(defaultTheme); SetGrammar(grammar); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } public void SetGrammarByLanguageId(string languageId) { string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); } public void SetGrammar(IGrammar grammar) { _grammar = grammar; GetOrCreateTransformer().SetGrammar(grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(ThemeName themeName) { IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); _textMateRegistry.SetTheme(rawTheme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { _editor.DocumentChanged -= OnEditorOnDocumentChanged; DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); DisposeTransformer(_transformer); } void OnEditorOnDocumentChanged(object sender, EventArgs args) { try { DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); _editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); _transformer = GetOrCreateTransformer(); _transformer.SetModel(_editor.Document, _tmModel); _tmModel.AddModelTokensChangedListener(_transformer); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } tmModel.Dispose(); } RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel; if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) return; transformer.Dispose(); } static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer) { if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Refactor the TextMate class to receive an abstract IRegistryOptions <DFF> @@ -17,51 +17,38 @@ namespace AvaloniaEdit.TextMate public static Installation InstallTextMate( this TextEditor editor, - ThemeName theme, - IGrammar grammar = null) + IRegistryOptions registryOptions) { - return new Installation(editor, theme, grammar); + return new Installation(editor, registryOptions); } public class Installation { - public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } - - public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) + public Installation(TextEditor editor, IRegistryOptions registryOptions) { - _textMateRegistryOptions = new RegistryOptions(defaultTheme); - _textMateRegistry = new Registry(_textMateRegistryOptions); + _textMateRegistry = new Registry(registryOptions); _editor = editor; - SetTheme(defaultTheme); - SetGrammar(grammar); + SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } - public void SetGrammarByLanguageId(string languageId) + public void SetGrammar(string scopeName) { - string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); - SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); - } + _grammar = _textMateRegistry.LoadGrammar(scopeName); - public void SetGrammar(IGrammar grammar) - { - _grammar = grammar; - - GetOrCreateTransformer().SetGrammar(grammar); + GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } - public void SetTheme(ThemeName themeName) + public void SetTheme(IRawTheme theme) { - IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); - - _textMateRegistry.SetTheme(rawTheme); + _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); @@ -116,7 +103,6 @@ namespace AvaloniaEdit.TextMate tmModel.Dispose(); } - RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel;
10
Refactor the TextMate class to receive an abstract IRegistryOptions
24
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10056752
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static void RegisterExceptionHandler(Action<Exception> handler) { _exceptionHandler = handler; } public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, IGrammar grammar = null) { return new Installation(editor, theme, grammar); } public class Installation { public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) { _textMateRegistryOptions = new RegistryOptions(defaultTheme); _textMateRegistry = new Registry(_textMateRegistryOptions); _editor = editor; SetTheme(defaultTheme); SetGrammar(grammar); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } public void SetGrammarByLanguageId(string languageId) { string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); } public void SetGrammar(IGrammar grammar) { _grammar = grammar; GetOrCreateTransformer().SetGrammar(grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(ThemeName themeName) { IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); _textMateRegistry.SetTheme(rawTheme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { _editor.DocumentChanged -= OnEditorOnDocumentChanged; DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); DisposeTransformer(_transformer); } void OnEditorOnDocumentChanged(object sender, EventArgs args) { try { DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); _editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); _transformer = GetOrCreateTransformer(); _transformer.SetModel(_editor.Document, _tmModel); _tmModel.AddModelTokensChangedListener(_transformer); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } tmModel.Dispose(); } RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel; if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) return; transformer.Dispose(); } static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer) { if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Refactor the TextMate class to receive an abstract IRegistryOptions <DFF> @@ -17,51 +17,38 @@ namespace AvaloniaEdit.TextMate public static Installation InstallTextMate( this TextEditor editor, - ThemeName theme, - IGrammar grammar = null) + IRegistryOptions registryOptions) { - return new Installation(editor, theme, grammar); + return new Installation(editor, registryOptions); } public class Installation { - public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } - - public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) + public Installation(TextEditor editor, IRegistryOptions registryOptions) { - _textMateRegistryOptions = new RegistryOptions(defaultTheme); - _textMateRegistry = new Registry(_textMateRegistryOptions); + _textMateRegistry = new Registry(registryOptions); _editor = editor; - SetTheme(defaultTheme); - SetGrammar(grammar); + SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } - public void SetGrammarByLanguageId(string languageId) + public void SetGrammar(string scopeName) { - string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); - SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); - } + _grammar = _textMateRegistry.LoadGrammar(scopeName); - public void SetGrammar(IGrammar grammar) - { - _grammar = grammar; - - GetOrCreateTransformer().SetGrammar(grammar); + GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } - public void SetTheme(ThemeName themeName) + public void SetTheme(IRawTheme theme) { - IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); - - _textMateRegistry.SetTheme(rawTheme); + _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); @@ -116,7 +103,6 @@ namespace AvaloniaEdit.TextMate tmModel.Dispose(); } - RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel;
10
Refactor the TextMate class to receive an abstract IRegistryOptions
24
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10056753
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static void RegisterExceptionHandler(Action<Exception> handler) { _exceptionHandler = handler; } public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, IGrammar grammar = null) { return new Installation(editor, theme, grammar); } public class Installation { public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) { _textMateRegistryOptions = new RegistryOptions(defaultTheme); _textMateRegistry = new Registry(_textMateRegistryOptions); _editor = editor; SetTheme(defaultTheme); SetGrammar(grammar); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } public void SetGrammarByLanguageId(string languageId) { string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); } public void SetGrammar(IGrammar grammar) { _grammar = grammar; GetOrCreateTransformer().SetGrammar(grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(ThemeName themeName) { IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); _textMateRegistry.SetTheme(rawTheme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { _editor.DocumentChanged -= OnEditorOnDocumentChanged; DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); DisposeTransformer(_transformer); } void OnEditorOnDocumentChanged(object sender, EventArgs args) { try { DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); _editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); _transformer = GetOrCreateTransformer(); _transformer.SetModel(_editor.Document, _tmModel); _tmModel.AddModelTokensChangedListener(_transformer); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } tmModel.Dispose(); } RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel; if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) return; transformer.Dispose(); } static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer) { if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Refactor the TextMate class to receive an abstract IRegistryOptions <DFF> @@ -17,51 +17,38 @@ namespace AvaloniaEdit.TextMate public static Installation InstallTextMate( this TextEditor editor, - ThemeName theme, - IGrammar grammar = null) + IRegistryOptions registryOptions) { - return new Installation(editor, theme, grammar); + return new Installation(editor, registryOptions); } public class Installation { - public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } - - public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) + public Installation(TextEditor editor, IRegistryOptions registryOptions) { - _textMateRegistryOptions = new RegistryOptions(defaultTheme); - _textMateRegistry = new Registry(_textMateRegistryOptions); + _textMateRegistry = new Registry(registryOptions); _editor = editor; - SetTheme(defaultTheme); - SetGrammar(grammar); + SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } - public void SetGrammarByLanguageId(string languageId) + public void SetGrammar(string scopeName) { - string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); - SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); - } + _grammar = _textMateRegistry.LoadGrammar(scopeName); - public void SetGrammar(IGrammar grammar) - { - _grammar = grammar; - - GetOrCreateTransformer().SetGrammar(grammar); + GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } - public void SetTheme(ThemeName themeName) + public void SetTheme(IRawTheme theme) { - IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); - - _textMateRegistry.SetTheme(rawTheme); + _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); @@ -116,7 +103,6 @@ namespace AvaloniaEdit.TextMate tmModel.Dispose(); } - RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel;
10
Refactor the TextMate class to receive an abstract IRegistryOptions
24
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10056754
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static void RegisterExceptionHandler(Action<Exception> handler) { _exceptionHandler = handler; } public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, IGrammar grammar = null) { return new Installation(editor, theme, grammar); } public class Installation { public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) { _textMateRegistryOptions = new RegistryOptions(defaultTheme); _textMateRegistry = new Registry(_textMateRegistryOptions); _editor = editor; SetTheme(defaultTheme); SetGrammar(grammar); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } public void SetGrammarByLanguageId(string languageId) { string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); } public void SetGrammar(IGrammar grammar) { _grammar = grammar; GetOrCreateTransformer().SetGrammar(grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(ThemeName themeName) { IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); _textMateRegistry.SetTheme(rawTheme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { _editor.DocumentChanged -= OnEditorOnDocumentChanged; DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); DisposeTransformer(_transformer); } void OnEditorOnDocumentChanged(object sender, EventArgs args) { try { DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); _editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); _transformer = GetOrCreateTransformer(); _transformer.SetModel(_editor.Document, _tmModel); _tmModel.AddModelTokensChangedListener(_transformer); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } tmModel.Dispose(); } RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel; if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) return; transformer.Dispose(); } static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer) { if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Refactor the TextMate class to receive an abstract IRegistryOptions <DFF> @@ -17,51 +17,38 @@ namespace AvaloniaEdit.TextMate public static Installation InstallTextMate( this TextEditor editor, - ThemeName theme, - IGrammar grammar = null) + IRegistryOptions registryOptions) { - return new Installation(editor, theme, grammar); + return new Installation(editor, registryOptions); } public class Installation { - public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } - - public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) + public Installation(TextEditor editor, IRegistryOptions registryOptions) { - _textMateRegistryOptions = new RegistryOptions(defaultTheme); - _textMateRegistry = new Registry(_textMateRegistryOptions); + _textMateRegistry = new Registry(registryOptions); _editor = editor; - SetTheme(defaultTheme); - SetGrammar(grammar); + SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } - public void SetGrammarByLanguageId(string languageId) + public void SetGrammar(string scopeName) { - string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); - SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); - } + _grammar = _textMateRegistry.LoadGrammar(scopeName); - public void SetGrammar(IGrammar grammar) - { - _grammar = grammar; - - GetOrCreateTransformer().SetGrammar(grammar); + GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } - public void SetTheme(ThemeName themeName) + public void SetTheme(IRawTheme theme) { - IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); - - _textMateRegistry.SetTheme(rawTheme); + _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); @@ -116,7 +103,6 @@ namespace AvaloniaEdit.TextMate tmModel.Dispose(); } - RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel;
10
Refactor the TextMate class to receive an abstract IRegistryOptions
24
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10056755
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static void RegisterExceptionHandler(Action<Exception> handler) { _exceptionHandler = handler; } public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, IGrammar grammar = null) { return new Installation(editor, theme, grammar); } public class Installation { public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) { _textMateRegistryOptions = new RegistryOptions(defaultTheme); _textMateRegistry = new Registry(_textMateRegistryOptions); _editor = editor; SetTheme(defaultTheme); SetGrammar(grammar); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } public void SetGrammarByLanguageId(string languageId) { string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); } public void SetGrammar(IGrammar grammar) { _grammar = grammar; GetOrCreateTransformer().SetGrammar(grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(ThemeName themeName) { IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); _textMateRegistry.SetTheme(rawTheme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { _editor.DocumentChanged -= OnEditorOnDocumentChanged; DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); DisposeTransformer(_transformer); } void OnEditorOnDocumentChanged(object sender, EventArgs args) { try { DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); _editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); _transformer = GetOrCreateTransformer(); _transformer.SetModel(_editor.Document, _tmModel); _tmModel.AddModelTokensChangedListener(_transformer); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } tmModel.Dispose(); } RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel; if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) return; transformer.Dispose(); } static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer) { if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Refactor the TextMate class to receive an abstract IRegistryOptions <DFF> @@ -17,51 +17,38 @@ namespace AvaloniaEdit.TextMate public static Installation InstallTextMate( this TextEditor editor, - ThemeName theme, - IGrammar grammar = null) + IRegistryOptions registryOptions) { - return new Installation(editor, theme, grammar); + return new Installation(editor, registryOptions); } public class Installation { - public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } - - public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) + public Installation(TextEditor editor, IRegistryOptions registryOptions) { - _textMateRegistryOptions = new RegistryOptions(defaultTheme); - _textMateRegistry = new Registry(_textMateRegistryOptions); + _textMateRegistry = new Registry(registryOptions); _editor = editor; - SetTheme(defaultTheme); - SetGrammar(grammar); + SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } - public void SetGrammarByLanguageId(string languageId) + public void SetGrammar(string scopeName) { - string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); - SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); - } + _grammar = _textMateRegistry.LoadGrammar(scopeName); - public void SetGrammar(IGrammar grammar) - { - _grammar = grammar; - - GetOrCreateTransformer().SetGrammar(grammar); + GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } - public void SetTheme(ThemeName themeName) + public void SetTheme(IRawTheme theme) { - IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); - - _textMateRegistry.SetTheme(rawTheme); + _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); @@ -116,7 +103,6 @@ namespace AvaloniaEdit.TextMate tmModel.Dispose(); } - RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel;
10
Refactor the TextMate class to receive an abstract IRegistryOptions
24
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10056756
<NME> TextMate.cs <BEF> using System; using System.Linq; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Registry; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public static class TextMate { public static void RegisterExceptionHandler(Action<Exception> handler) { _exceptionHandler = handler; } public static Installation InstallTextMate( this TextEditor editor, ThemeName theme, IGrammar grammar = null) { return new Installation(editor, theme, grammar); } public class Installation { public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) { _textMateRegistryOptions = new RegistryOptions(defaultTheme); _textMateRegistry = new Registry(_textMateRegistryOptions); _editor = editor; SetTheme(defaultTheme); SetGrammar(grammar); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } public void SetGrammarByLanguageId(string languageId) { string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); } public void SetGrammar(IGrammar grammar) { _grammar = grammar; GetOrCreateTransformer().SetGrammar(grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(ThemeName themeName) { IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); _textMateRegistry.SetTheme(rawTheme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); public void SetGrammar(string scopeName) { _grammar = _textMateRegistry.LoadGrammar(scopeName); GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } public void SetTheme(IRawTheme theme) { _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); _tmModel?.InvalidateLine(0); _editorModel?.InvalidateViewPortLines(); } public void Dispose() { _editor.DocumentChanged -= OnEditorOnDocumentChanged; DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); DisposeTransformer(_transformer); } void OnEditorOnDocumentChanged(object sender, EventArgs args) { try { DisposeEditorModel(_editorModel); DisposeTMModel(_tmModel, _transformer); _editorModel = new TextEditorModel(_editor.TextArea.TextView, _editor.Document, _exceptionHandler); _tmModel = new TMModel(_editorModel); _tmModel.SetGrammar(_grammar); _transformer = GetOrCreateTransformer(); _transformer.SetModel(_editor.Document, _tmModel); _tmModel.AddModelTokensChangedListener(_transformer); } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } tmModel.Dispose(); } RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel; if (transformer is null) { transformer = new TextMateColoringTransformer( _editor.TextArea.TextView, _exceptionHandler); _editor.TextArea.TextView.LineTransformers.Add(transformer); } return transformer; } static void DisposeTransformer(TextMateColoringTransformer transformer) { if (transformer == null) return; transformer.Dispose(); } static void DisposeTMModel(TMModel tmModel, TextMateColoringTransformer transformer) { if (tmModel == null) return; if (transformer != null) tmModel.RemoveModelTokensChangedListener(transformer); tmModel.Dispose(); } static void DisposeEditorModel(TextEditorModel editorModel) { if (editorModel == null) return; editorModel.Dispose(); } } static Action<Exception> _exceptionHandler; } } <MSG> Refactor the TextMate class to receive an abstract IRegistryOptions <DFF> @@ -17,51 +17,38 @@ namespace AvaloniaEdit.TextMate public static Installation InstallTextMate( this TextEditor editor, - ThemeName theme, - IGrammar grammar = null) + IRegistryOptions registryOptions) { - return new Installation(editor, theme, grammar); + return new Installation(editor, registryOptions); } public class Installation { - public RegistryOptions RegistryOptions { get { return _textMateRegistryOptions; } } - - public Installation(TextEditor editor, ThemeName defaultTheme, IGrammar grammar) + public Installation(TextEditor editor, IRegistryOptions registryOptions) { - _textMateRegistryOptions = new RegistryOptions(defaultTheme); - _textMateRegistry = new Registry(_textMateRegistryOptions); + _textMateRegistry = new Registry(registryOptions); _editor = editor; - SetTheme(defaultTheme); - SetGrammar(grammar); + SetTheme(registryOptions.GetDefaultTheme()); editor.DocumentChanged += OnEditorOnDocumentChanged; OnEditorOnDocumentChanged(editor, EventArgs.Empty); } - public void SetGrammarByLanguageId(string languageId) + public void SetGrammar(string scopeName) { - string scopeName = _textMateRegistryOptions.GetScopeByLanguageId(languageId); - SetGrammar((scopeName == null) ? null : _textMateRegistry.LoadGrammar(scopeName)); - } + _grammar = _textMateRegistry.LoadGrammar(scopeName); - public void SetGrammar(IGrammar grammar) - { - _grammar = grammar; - - GetOrCreateTransformer().SetGrammar(grammar); + GetOrCreateTransformer().SetGrammar(_grammar); _editor.TextArea.TextView.Redraw(); } - public void SetTheme(ThemeName themeName) + public void SetTheme(IRawTheme theme) { - IRawTheme rawTheme = _textMateRegistryOptions.LoadTheme(themeName); - - _textMateRegistry.SetTheme(rawTheme); + _textMateRegistry.SetTheme(theme); GetOrCreateTransformer().SetTheme(_textMateRegistry.GetTheme()); @@ -116,7 +103,6 @@ namespace AvaloniaEdit.TextMate tmModel.Dispose(); } - RegistryOptions _textMateRegistryOptions; Registry _textMateRegistry; TextEditor _editor; TextEditorModel _editorModel;
10
Refactor the TextMate class to receive an abstract IRegistryOptions
24
.cs
TextMate/TextMate
mit
AvaloniaUI/AvaloniaEdit
10056757
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> ``` You can also use more advanced syntax for more options: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` 1. Load a single file ```javascript loadjs('/path/to/foo.js', { success: function() { /* foo.js loaded */} }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js & bar.js loaded */ } }); ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Fetch JavaScript and CSS files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.js'], { success: function() { /* foo.css and bar.js loaded */ } }); ``` 1. Force treating file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], { success: function() { /* cssfile.custom loaded as stylesheet */ } }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ } }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ } }); } ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Execute a callback after bundle finishes loading ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ } }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', { success: function() { /* foo.js loaded */ } }) .ready('bar', { success: function() { /* bar.js loaded */ } }); ``` 1. Compose more complex dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], { success: function() { // run code after dependencies have been met } }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` ## Directory structure loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Fixed README markdown <DFF> @@ -68,179 +68,178 @@ Note: LoadJS treats empty CSS files as load failures in IE (to get around lack o 1. Load a single file - ```javascript - loadjs('/path/to/foo.js', { - success: function() { /* foo.js loaded */} - }); - ``` + ```javascript + loadjs('/path/to/foo.js', { + success: function() { /* foo.js loaded */} + }); + ``` 1. Fetch files in parallel and load them asynchronously - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], { - success: function() { /* foo.js & bar.js loaded */ } - }); - ``` + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], { + success: function() { /* foo.js & bar.js loaded */ } + }); + ``` 1. Fetch files in parallel and load them in series - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], { - success: function() { /* foo.js and bar.js loaded in series */ }, - async: false - }); - ``` + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], { + success: function() { /* foo.js and bar.js loaded in series */ }, + async: false + }); + ``` 1. Fetch JavaScript and CSS files - ```javascript - loadjs(['/path/to/foo.css', '/path/to/bar.js'], { - success: function() { /* foo.css and bar.js loaded */ } - }); - ``` + ```javascript + loadjs(['/path/to/foo.css', '/path/to/bar.js'], { + success: function() { /* foo.css and bar.js loaded */ } + }); + ``` 1. Force treating file as CSS stylesheet - ```javascript - loadjs(['css!/path/to/cssfile.custom'], { - success: function() { /* cssfile.custom loaded as stylesheet */ } - }); - ``` + ```javascript + loadjs(['css!/path/to/cssfile.custom'], { + success: function() { /* cssfile.custom loaded as stylesheet */ } + }); + ``` 1. Add a bundle id - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { - success: function() { /* foo.js & bar.js loaded */ } - }); - ``` - -1. Check if bundle has already been defined - - ```javascript - if (!loadjs.isDefined('foobar')) { + ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ } }); - } - ``` + ``` + +1. Check if bundle has already been defined + + ```javascript + if (!loadjs.isDefined('foobar')) { + loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { + success: function() { /* foo.js & bar.js loaded */ } + }); + } + ``` 1. Add an error callback - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { - success: function() { /* foo.js & bar.js loaded */ }, - error: function(pathsNotFound) { /* at least one path didn't load */ } - }); - ``` + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { + success: function() { /* foo.js & bar.js loaded */ }, + error: function(pathsNotFound) { /* at least one path didn't load */ } + }); + ``` 1. Retry files before calling the error callback - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { - success: function() { /* foo.js & bar.js loaded */ }, - error: function(pathsNotFound) { /* at least one path didn't load */ }, - numRetries: 3 - }); - ``` + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { + success: function() { /* foo.js & bar.js loaded */ }, + error: function(pathsNotFound) { /* at least one path didn't load */ }, + numRetries: 3 + }); + ``` 1. Execute a callback before script tags are embedded - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], { - success: function() {}, - error: function(pathsNotFound) {}, - before: function(path, scriptEl) { - /* called for each script node before being embedded */ - if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; - } - }); - ``` + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], { + success: function() {}, + error: function(pathsNotFound) {}, + before: function(path, scriptEl) { + /* called for each script node before being embedded */ + if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; + } + }); + ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) - ```javascript - loadjs(['/path/to/foo.js'], { - success: function() {}, - error: function(pathsNotFound) {}, - before: function(path, scriptEl) { - document.body.appendChild(scriptEl); + ```javascript + loadjs(['/path/to/foo.js'], { + success: function() {}, + error: function(pathsNotFound) {}, + before: function(path, scriptEl) { + document.body.appendChild(scriptEl); - /* return `false` to bypass default DOM insertion mechanism */ - return false; - } - }); - ``` + /* return `false` to bypass default DOM insertion mechanism */ + return false; + } + }); + ``` 1. Execute a callback after bundle finishes loading - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); - loadjs.ready('foobar', { - success: function() { /* foo.js & bar.js loaded */ } - }); - ``` + loadjs.ready('foobar', { + success: function() { /* foo.js & bar.js loaded */ } + }); + ``` 1. Chain .ready() together - ```javascript - loadjs('/path/to/foo.js', 'foo'); - loadjs('/path/to/bar.js', 'bar'); + ```javascript + loadjs('/path/to/foo.js', 'foo'); + loadjs('/path/to/bar.js', 'bar'); - loadjs - .ready('foo', { - success: function() { /* foo.js loaded */ } - }) - .ready('bar', { - success: function() { /* bar.js loaded */ } - }); - ``` + loadjs + .ready('foo', { + success: function() { /* foo.js loaded */ } + }) + .ready('bar', { + success: function() { /* bar.js loaded */ } + }); + ``` 1. Compose more complex dependency lists - ```javascript - loadjs('/path/to/foo.js', 'foo'); - loadjs('/path/to/bar.js', 'bar'); - loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); - - // wait for multiple depdendencies - loadjs.ready(['foo', 'bar', 'thunk'], { - success: function() { - // foo.js & bar.js & thunkor.js & thunky.js loaded - }, - error: function(depsNotFound) { - if (depsNotFound.indexOf('foo') > -1) {}; // foo failed - if (depsNotFound.indexOf('bar') > -1) {}; // bar failed - if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed - } - }); - ``` + ```javascript + loadjs('/path/to/foo.js', 'foo'); + loadjs('/path/to/bar.js', 'bar'); + loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); + + // wait for multiple depdendencies + loadjs.ready(['foo', 'bar', 'thunk'], { + success: function() { + // foo.js & bar.js & thunkor.js & thunky.js loaded + }, + error: function(depsNotFound) { + if (depsNotFound.indexOf('foo') > -1) {}; // foo failed + if (depsNotFound.indexOf('bar') > -1) {}; // bar failed + if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed + } + }); + ``` 1. Use .done() for more control - ```javascript - loadjs.ready(['dependency1', 'dependency2'], { - success: function() { - // run code after dependencies have been met - } - }); + ```javascript + loadjs.ready(['dependency1', 'dependency2'], { + success: function() { + // run code after dependencies have been met + } + }); - function fn1() { - loadjs.done('dependency1'); - } + function fn1() { + loadjs.done('dependency1'); + } - function fn2() { - loadjs.done('dependency2'); - } - ``` + function fn2() { + loadjs.done('dependency2'); + } + ``` 1. Reset dependency trackers - - ```javascript - loadjs.reset(); - ``` + ```javascript + loadjs.reset(); + ``` ## Directory structure @@ -265,59 +264,59 @@ loadjs/ 1. Install dependencies - * [nodejs](http://nodejs.org/) - * [npm](https://www.npmjs.org/) - * http-server (via npm) + * [nodejs](http://nodejs.org/) + * [npm](https://www.npmjs.org/) + * http-server (via npm) 1. Clone repository - ```bash - $ git clone [email protected]:muicss/loadjs.git - $ cd loadjs - ``` + ```bash + $ git clone [email protected]:muicss/loadjs.git + $ cd loadjs + ``` 1. Install node dependencies using npm - ```bash - $ npm install - ``` + ```bash + $ npm install + ``` 1. Build examples - ```bash - $ npm run build-examples - ``` + ```bash + $ npm run build-examples + ``` - To view the examples you can use any static file server. To use the `nodejs` http-server module: + To view the examples you can use any static file server. To use the `nodejs` http-server module: - ```bash - $ npm install http-server - $ npm run http-server -- -p 3000 - ``` + ```bash + $ npm install http-server + $ npm run http-server -- -p 3000 + ``` - Then visit [http://localhost:3000/examples](http://localhost:3000/examples) + Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files - ```bash - $ npm run build-dist - ``` + ```bash + $ npm run build-dist + ``` - The files will be located in the `dist` directory. + The files will be located in the `dist` directory. 1. Run tests - To run the browser tests first build the `loadjs` library: + To run the browser tests first build the `loadjs` library: - ```bash - $ npm run build-tests - ``` + ```bash + $ npm run build-tests + ``` - Then visit [http://localhost:3000/test](http://localhost:3000/test) + Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files - ```bash - $ npm run build-all - ``` + ```bash + $ npm run build-all + ```
153
Fixed README markdown
154
.md
md
mit
muicss/loadjs
10056758
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); </script> ``` You can also use more advanced syntax for more options: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` 1. Load a single file ```javascript loadjs('/path/to/foo.js', { success: function() { /* foo.js loaded */} }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js & bar.js loaded */ } }); ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Fetch JavaScript and CSS files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.js'], { success: function() { /* foo.css and bar.js loaded */ } }); ``` 1. Force treating file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], { success: function() { /* cssfile.custom loaded as stylesheet */ } }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ } }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ } }); } ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Execute a callback after bundle finishes loading ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ } }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', { success: function() { /* foo.js loaded */ } }) .ready('bar', { success: function() { /* bar.js loaded */ } }); ``` 1. Compose more complex dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], { success: function() { // run code after dependencies have been met } }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` ## Directory structure loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Fixed README markdown <DFF> @@ -68,179 +68,178 @@ Note: LoadJS treats empty CSS files as load failures in IE (to get around lack o 1. Load a single file - ```javascript - loadjs('/path/to/foo.js', { - success: function() { /* foo.js loaded */} - }); - ``` + ```javascript + loadjs('/path/to/foo.js', { + success: function() { /* foo.js loaded */} + }); + ``` 1. Fetch files in parallel and load them asynchronously - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], { - success: function() { /* foo.js & bar.js loaded */ } - }); - ``` + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], { + success: function() { /* foo.js & bar.js loaded */ } + }); + ``` 1. Fetch files in parallel and load them in series - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], { - success: function() { /* foo.js and bar.js loaded in series */ }, - async: false - }); - ``` + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], { + success: function() { /* foo.js and bar.js loaded in series */ }, + async: false + }); + ``` 1. Fetch JavaScript and CSS files - ```javascript - loadjs(['/path/to/foo.css', '/path/to/bar.js'], { - success: function() { /* foo.css and bar.js loaded */ } - }); - ``` + ```javascript + loadjs(['/path/to/foo.css', '/path/to/bar.js'], { + success: function() { /* foo.css and bar.js loaded */ } + }); + ``` 1. Force treating file as CSS stylesheet - ```javascript - loadjs(['css!/path/to/cssfile.custom'], { - success: function() { /* cssfile.custom loaded as stylesheet */ } - }); - ``` + ```javascript + loadjs(['css!/path/to/cssfile.custom'], { + success: function() { /* cssfile.custom loaded as stylesheet */ } + }); + ``` 1. Add a bundle id - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { - success: function() { /* foo.js & bar.js loaded */ } - }); - ``` - -1. Check if bundle has already been defined - - ```javascript - if (!loadjs.isDefined('foobar')) { + ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ } }); - } - ``` + ``` + +1. Check if bundle has already been defined + + ```javascript + if (!loadjs.isDefined('foobar')) { + loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { + success: function() { /* foo.js & bar.js loaded */ } + }); + } + ``` 1. Add an error callback - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { - success: function() { /* foo.js & bar.js loaded */ }, - error: function(pathsNotFound) { /* at least one path didn't load */ } - }); - ``` + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { + success: function() { /* foo.js & bar.js loaded */ }, + error: function(pathsNotFound) { /* at least one path didn't load */ } + }); + ``` 1. Retry files before calling the error callback - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { - success: function() { /* foo.js & bar.js loaded */ }, - error: function(pathsNotFound) { /* at least one path didn't load */ }, - numRetries: 3 - }); - ``` + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { + success: function() { /* foo.js & bar.js loaded */ }, + error: function(pathsNotFound) { /* at least one path didn't load */ }, + numRetries: 3 + }); + ``` 1. Execute a callback before script tags are embedded - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], { - success: function() {}, - error: function(pathsNotFound) {}, - before: function(path, scriptEl) { - /* called for each script node before being embedded */ - if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; - } - }); - ``` + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], { + success: function() {}, + error: function(pathsNotFound) {}, + before: function(path, scriptEl) { + /* called for each script node before being embedded */ + if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; + } + }); + ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) - ```javascript - loadjs(['/path/to/foo.js'], { - success: function() {}, - error: function(pathsNotFound) {}, - before: function(path, scriptEl) { - document.body.appendChild(scriptEl); + ```javascript + loadjs(['/path/to/foo.js'], { + success: function() {}, + error: function(pathsNotFound) {}, + before: function(path, scriptEl) { + document.body.appendChild(scriptEl); - /* return `false` to bypass default DOM insertion mechanism */ - return false; - } - }); - ``` + /* return `false` to bypass default DOM insertion mechanism */ + return false; + } + }); + ``` 1. Execute a callback after bundle finishes loading - ```javascript - loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); + ```javascript + loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); - loadjs.ready('foobar', { - success: function() { /* foo.js & bar.js loaded */ } - }); - ``` + loadjs.ready('foobar', { + success: function() { /* foo.js & bar.js loaded */ } + }); + ``` 1. Chain .ready() together - ```javascript - loadjs('/path/to/foo.js', 'foo'); - loadjs('/path/to/bar.js', 'bar'); + ```javascript + loadjs('/path/to/foo.js', 'foo'); + loadjs('/path/to/bar.js', 'bar'); - loadjs - .ready('foo', { - success: function() { /* foo.js loaded */ } - }) - .ready('bar', { - success: function() { /* bar.js loaded */ } - }); - ``` + loadjs + .ready('foo', { + success: function() { /* foo.js loaded */ } + }) + .ready('bar', { + success: function() { /* bar.js loaded */ } + }); + ``` 1. Compose more complex dependency lists - ```javascript - loadjs('/path/to/foo.js', 'foo'); - loadjs('/path/to/bar.js', 'bar'); - loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); - - // wait for multiple depdendencies - loadjs.ready(['foo', 'bar', 'thunk'], { - success: function() { - // foo.js & bar.js & thunkor.js & thunky.js loaded - }, - error: function(depsNotFound) { - if (depsNotFound.indexOf('foo') > -1) {}; // foo failed - if (depsNotFound.indexOf('bar') > -1) {}; // bar failed - if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed - } - }); - ``` + ```javascript + loadjs('/path/to/foo.js', 'foo'); + loadjs('/path/to/bar.js', 'bar'); + loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); + + // wait for multiple depdendencies + loadjs.ready(['foo', 'bar', 'thunk'], { + success: function() { + // foo.js & bar.js & thunkor.js & thunky.js loaded + }, + error: function(depsNotFound) { + if (depsNotFound.indexOf('foo') > -1) {}; // foo failed + if (depsNotFound.indexOf('bar') > -1) {}; // bar failed + if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed + } + }); + ``` 1. Use .done() for more control - ```javascript - loadjs.ready(['dependency1', 'dependency2'], { - success: function() { - // run code after dependencies have been met - } - }); + ```javascript + loadjs.ready(['dependency1', 'dependency2'], { + success: function() { + // run code after dependencies have been met + } + }); - function fn1() { - loadjs.done('dependency1'); - } + function fn1() { + loadjs.done('dependency1'); + } - function fn2() { - loadjs.done('dependency2'); - } - ``` + function fn2() { + loadjs.done('dependency2'); + } + ``` 1. Reset dependency trackers - - ```javascript - loadjs.reset(); - ``` + ```javascript + loadjs.reset(); + ``` ## Directory structure @@ -265,59 +264,59 @@ loadjs/ 1. Install dependencies - * [nodejs](http://nodejs.org/) - * [npm](https://www.npmjs.org/) - * http-server (via npm) + * [nodejs](http://nodejs.org/) + * [npm](https://www.npmjs.org/) + * http-server (via npm) 1. Clone repository - ```bash - $ git clone [email protected]:muicss/loadjs.git - $ cd loadjs - ``` + ```bash + $ git clone [email protected]:muicss/loadjs.git + $ cd loadjs + ``` 1. Install node dependencies using npm - ```bash - $ npm install - ``` + ```bash + $ npm install + ``` 1. Build examples - ```bash - $ npm run build-examples - ``` + ```bash + $ npm run build-examples + ``` - To view the examples you can use any static file server. To use the `nodejs` http-server module: + To view the examples you can use any static file server. To use the `nodejs` http-server module: - ```bash - $ npm install http-server - $ npm run http-server -- -p 3000 - ``` + ```bash + $ npm install http-server + $ npm run http-server -- -p 3000 + ``` - Then visit [http://localhost:3000/examples](http://localhost:3000/examples) + Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files - ```bash - $ npm run build-dist - ``` + ```bash + $ npm run build-dist + ``` - The files will be located in the `dist` directory. + The files will be located in the `dist` directory. 1. Run tests - To run the browser tests first build the `loadjs` library: + To run the browser tests first build the `loadjs` library: - ```bash - $ npm run build-tests - ``` + ```bash + $ npm run build-tests + ``` - Then visit [http://localhost:3000/test](http://localhost:3000/test) + Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files - ```bash - $ npm run build-all - ``` + ```bash + $ npm run build-all + ```
153
Fixed README markdown
154
.md
md
mit
muicss/loadjs
10056759
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056760
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056761
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056762
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056763
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056764
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056765
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056766
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056767
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056768
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056769
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056770
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056771
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056772
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056773
<NME> TextMateColoringTransformer.cs <BEF> using System; using System.Buffers; using System.Collections.Generic; using Avalonia.Media; using Avalonia.Media.Immutable; using Avalonia.Threading; using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using TextMateSharp.Grammars; using TextMateSharp.Model; using TextMateSharp.Themes; namespace AvaloniaEdit.TextMate { public class TextMateColoringTransformer : GenericLineTransformer, IModelTokensChangedListener, ForegroundTextTransformation.IColorMap { private Theme _theme; private IGrammar _grammar; private TMModel _model; private TextDocument _document; private TextView _textView; private Action<Exception> _exceptionHandler; private volatile bool _areVisualLinesValid = false; private volatile int _firstVisibleLineIndex = -1; private volatile int _lastVisibleLineIndex = -1; private readonly Dictionary<int, IBrush> _brushes; public TextMateColoringTransformer( TextView textView, Action<Exception> exceptionHandler) : base(exceptionHandler) { _textView = textView; _exceptionHandler = exceptionHandler; _brushes = new Dictionary<int, IBrush>(); _textView.VisualLinesChanged += TextView_VisualLinesChanged; } public void SetModel(TextDocument document, TMModel model) { _areVisualLinesValid = false; _document = document; _model = model; if (_grammar != null) { _model.SetGrammar(_grammar); } } private void TextView_VisualLinesChanged(object sender, EventArgs e) { try { if (!_textView.VisualLinesValid || _textView.VisualLines.Count == 0) return; _areVisualLinesValid = true; _firstVisibleLineIndex = _textView.VisualLines[0].FirstDocumentLine.LineNumber - 1; _lastVisibleLineIndex = _textView.VisualLines[_textView.VisualLines.Count - 1].LastDocumentLine.LineNumber - 1; } catch (Exception ex) { _exceptionHandler?.Invoke(ex); } } public void Dispose() { _textView.VisualLinesChanged -= TextView_VisualLinesChanged; } public void SetTheme(Theme theme) { _theme = theme; _brushes.Clear(); var map = _theme.GetColorMap(); foreach (var color in map) { var id = _theme.GetColorId(color); _brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color))); } } public void SetGrammar(IGrammar grammar) { return _brushes.ContainsKey(foregroundColor); } IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) { return _brushes[foregroundColor]; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) return null; _brushes.TryGetValue(colorId, out IBrush result); return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) { try { if (_model == null) return; int lineNumber = line.LineNumber; var tokens = _model.GetLineTokens(lineNumber - 1); if (tokens == null) return; var transformsInLine = ArrayPool<ForegroundTextTransformation>.Shared.Rent(tokens.Count); try { GetLineTransformations(lineNumber, tokens, transformsInLine); for (int i = 0; i < tokens.Count; i++) { if (transformsInLine[i] == null) continue; transformsInLine[i].Transform(this, line); } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; foreach (var themeRule in _theme.Match(token.Scopes)) { if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) { _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, lineOffset + endIndex, themeRule.foreground)); break; } } } } transformations[i] = null; continue; } var lineOffset = _document.GetLineByNumber(lineNumber).Offset; int foreground = 0; int background = 0; int fontStyle = 0; foreach (var themeRule in _theme.Match(token.Scopes)) { if (foreground == 0 && themeRule.foreground > 0) foreground = themeRule.foreground; if (background == 0 && themeRule.background > 0) background = themeRule.background; if (fontStyle == 0 && themeRule.fontStyle > 0) fontStyle = themeRule.fontStyle; } if (transformations[i] == null) transformations[i] = new ForegroundTextTransformation(); transformations[i].ColorMap = this; transformations[i].ExceptionHandler = _exceptionHandler; transformations[i].StartOffset = lineOffset + startIndex; transformations[i].EndOffset = lineOffset + endIndex; transformations[i].ForegroundColor = foreground; transformations[i].BackgroundColor = background; transformations[i].FontStyle = fontStyle; } } public void ModelTokensChanged(ModelTokensChangedEvent e) { if (e.Ranges == null) return; if (_model == null || _model.IsStopped) return; int firstChangedLineIndex = int.MaxValue; int lastChangedLineIndex = -1; foreach (var range in e.Ranges) { firstChangedLineIndex = Math.Min(range.FromLineNumber - 1, firstChangedLineIndex); lastChangedLineIndex = Math.Max(range.ToLineNumber - 1, lastChangedLineIndex); } if (_areVisualLinesValid) { bool changedLinesAreNotVisible = ((firstChangedLineIndex < _firstVisibleLineIndex && lastChangedLineIndex < _firstVisibleLineIndex) || (firstChangedLineIndex > _lastVisibleLineIndex && lastChangedLineIndex > _lastVisibleLineIndex)); if (changedLinesAreNotVisible) return; } Dispatcher.UIThread.Post(() => { int firstLineIndexToRedraw = Math.Max(firstChangedLineIndex, _firstVisibleLineIndex); int lastLineIndexToRedrawLine = Math.Min(lastChangedLineIndex, _lastVisibleLineIndex); int totalLines = _document.Lines.Count - 1; firstLineIndexToRedraw = Clamp(firstLineIndexToRedraw, 0, totalLines); lastLineIndexToRedrawLine = Clamp(lastLineIndexToRedrawLine, 0, totalLines); DocumentLine firstLineToRedraw = _document.Lines[firstLineIndexToRedraw]; DocumentLine lastLineToRedraw = _document.Lines[lastLineIndexToRedrawLine]; _textView.Redraw( firstLineToRedraw.Offset, (lastLineToRedraw.Offset + lastLineToRedraw.TotalLength) - firstLineToRedraw.Offset); }); } static int Clamp(int value, int min, int max) { if (value < min) return min; if (value > max) return max; return value; } static string NormalizeColor(string color) { if (color.Length == 9) { Span<char> normalizedColor = stackalloc char[] { '#', color[7], color[8], color[1], color[2], color[3], color[4], color[5], color[6] }; return normalizedColor.ToString(); } return color; } } } <MSG> Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule Additionally, change the IColorMap.GetBrush impl to return null when the colorId is not found in the dictionary. <DFF> @@ -100,9 +100,11 @@ namespace AvaloniaEdit.TextMate return _brushes.ContainsKey(foregroundColor); } - IBrush ForegroundTextTransformation.IColorMap.GetForegroundBrush(int foregroundColor) + IBrush ForegroundTextTransformation.IColorMap.GetBrush(int color) { - return _brushes[foregroundColor]; + IBrush result = null; + _brushes.TryGetValue(color, out result); + return result; } protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context) @@ -142,16 +144,24 @@ namespace AvaloniaEdit.TextMate var lineOffset = _document.GetLineByNumber(lineNumber).Offset; + int foreground = 0; + int background = 0; + int fontStyle = 0; + foreach (var themeRule in _theme.Match(token.Scopes)) { - if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground)) - { - _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, - lineOffset + endIndex, themeRule.foreground)); + if (foreground == 0 && themeRule.foreground > 0) + foreground = themeRule.foreground; + + if (background == 0 && themeRule.background > 0) + background = themeRule.background; - break; - } + if (fontStyle == 0 && themeRule.fontStyle > 0) + fontStyle = themeRule.fontStyle; } + + _transformations.Add(new ForegroundTextTransformation(this, lineOffset + startIndex, + lineOffset + endIndex, foreground, background, fontStyle)); } }
18
Change the TextMateColoring transformer to get bg, and fontstyle from the themeRule
8
.cs
TextMate/TextMateColoringTransformer
mit
AvaloniaUI/AvaloniaEdit
10056774
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056775
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056776
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056777
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056778
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056779
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056780
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056781
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056782
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056783
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056784
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056785
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056786
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056787
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056788
<NME> FoldingMargin.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.Collections.Generic; using System.Linq; using Avalonia; using AvaloniaEdit.Editing; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Media; using Avalonia.Media.TextFormatting; namespace AvaloniaEdit.Folding { /// <summary> /// A margin that shows markers for foldings and allows to expand/collapse the foldings. /// </summary> public class FoldingMargin : AbstractMargin { /// <summary> /// Gets/Sets the folding manager from which the foldings should be shown. /// </summary> public FoldingManager FoldingManager { get; set; } internal const double SizeFactor = Constants.PixelPerPoint; static FoldingMargin() { FoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); FoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBrushProperty.Changed.Subscribe(OnUpdateBrushes); SelectedFoldingMarkerBackgroundBrushProperty.Changed.Subscribe(OnUpdateBrushes); } #region Brushes /// <summary> /// FoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBrush", Brushes.Gray, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of folding markers. /// </summary> public IBrush FoldingMarkerBrush { get => GetValue(FoldingMarkerBrushProperty); set => SetValue(FoldingMarkerBrushProperty, value); } /// <summary> /// FoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> FoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("FoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of folding markers. /// </summary> public IBrush FoldingMarkerBackgroundBrush { get => GetValue(FoldingMarkerBackgroundBrushProperty); set => SetValue(FoldingMarkerBackgroundBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBrush", Brushes.Black, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the lines of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBrush { get => GetValue(SelectedFoldingMarkerBrushProperty); set => SetValue(SelectedFoldingMarkerBrushProperty, value); } /// <summary> /// SelectedFoldingMarkerBackgroundBrush dependency property. /// </summary> public static readonly AttachedProperty<IBrush> SelectedFoldingMarkerBackgroundBrushProperty = AvaloniaProperty.RegisterAttached<FoldingMargin, Control, IBrush>("SelectedFoldingMarkerBackgroundBrush", Brushes.White, inherits: true); /// <summary> /// Gets/sets the Brush used for displaying the background of selected folding markers. /// </summary> public IBrush SelectedFoldingMarkerBackgroundBrush { get => GetValue(SelectedFoldingMarkerBackgroundBrushProperty); set => SetValue(SelectedFoldingMarkerBackgroundBrushProperty, value); } private static void OnUpdateBrushes(AvaloniaPropertyChangedEventArgs e) { FoldingMargin m = null; if (e.Sender is FoldingMargin margin) m = margin; else if (e.Sender is TextEditor editor) m = editor.TextArea.LeftMargins.FirstOrDefault(c => c is FoldingMargin) as FoldingMargin; if (m == null) return; if (e.Property.Name == FoldingMarkerBrushProperty.Name) { m._foldingControlPen = new Pen((IBrush)e.NewValue); } if (e.Property.Name == SelectedFoldingMarkerBrushProperty.Name) { m._selectedFoldingControlPen = new Pen((IBrush)e.NewValue); } } #endregion /// <inheritdoc/> protected override Size MeasureOverride(Size availableSize) { foreach (var m in _markers) { m.Measure(availableSize); } var width = SizeFactor * GetValue(TextBlock.FontSizeProperty); return new Size(PixelSnapHelpers.RoundToOdd(width, PixelSnapHelpers.GetPixelSize(this).Width), 0); } /// <inheritdoc/> protected override Size ArrangeOverride(Size finalSize) { var pixelSize = PixelSnapHelpers.GetPixelSize(this); foreach (var m in _markers) { var visualColumn = m.VisualLine.GetVisualColumn(m.FoldingSection.StartOffset - m.VisualLine.FirstDocumentLine.Offset); var textLine = m.VisualLine.GetTextLine(visualColumn); var yPos = m.VisualLine.GetTextLineVisualYPosition(textLine, VisualYPosition.TextMiddle) - TextView.VerticalOffset; yPos -= m.DesiredSize.Height / 2; var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } return base.ArrangeOverride(finalSize); } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); protected override void OnTextViewVisualLinesChanged() { foreach (var m in _markers) { VisualChildren.Remove(m); } _markers.Clear(); InvalidateVisual(); if (TextView != null && FoldingManager != null && TextView.VisualLinesValid) { foreach (var line in TextView.VisualLines) { var fs = FoldingManager.GetNextFolding(line.FirstDocumentLine.Offset); if (fs?.StartOffset <= line.LastDocumentLine.Offset + line.LastDocumentLine.Length) { var m = new FoldingMarginMarker { IsExpanded = !fs.IsFolded, VisualLine = line, FoldingSection = fs }; _markers.Add(m); VisualChildren.Add(m); m.PropertyChanged += (o, args) => { if (args.Property == IsPointerOverProperty) { InvalidateVisual(); } }; InvalidateMeasure(); } } } } private Pen _foldingControlPen = new Pen(FoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); private Pen _selectedFoldingControlPen = new Pen(SelectedFoldingMarkerBrushProperty.GetDefaultValue(typeof(FoldingMargin))); /// <inheritdoc/> public override void Render(DrawingContext drawingContext) { if (TextView == null || !TextView.VisualLinesValid) return; if (TextView.VisualLines.Count == 0 || FoldingManager == null) return; var allTextLines = TextView.VisualLines.SelectMany(vl => vl.TextLines).ToList(); var colors = new Pen[allTextLines.Count + 1]; var endMarker = new Pen[allTextLines.Count]; CalculateFoldLinesForFoldingsActiveAtStart(allTextLines, colors, endMarker); CalculateFoldLinesForMarkers(allTextLines, colors, endMarker); DrawFoldLines(drawingContext, colors, endMarker); } /// <summary> /// Calculates fold lines for all folding sections that start in front of the current view /// and run into the current view. /// </summary> private void CalculateFoldLinesForFoldingsActiveAtStart(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { var viewStartOffset = TextView.VisualLines[0].FirstDocumentLine.Offset; var viewEndOffset = TextView.VisualLines.Last().LastDocumentLine.EndOffset; var foldings = FoldingManager.GetFoldingsContaining(viewStartOffset); var maxEndOffset = 0; foreach (var fs in foldings) { var end = fs.EndOffset; if (end <= viewEndOffset && !fs.IsFolded) { var textLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (textLineNr >= 0) { endMarker[textLineNr] = _foldingControlPen; } } if (end > maxEndOffset && fs.StartOffset < viewStartOffset) { maxEndOffset = end; } } if (maxEndOffset > 0) { if (maxEndOffset > viewEndOffset) { for (var i = 0; i < colors.Length; i++) { colors[i] = _foldingControlPen; } } else { var maxTextLine = GetTextLineIndexFromOffset(allTextLines, maxEndOffset); for (var i = 0; i <= maxTextLine; i++) { colors[i] = _foldingControlPen; } } } } /// <summary> /// Calculates fold lines for all folding sections that start inside the current view /// </summary> private void CalculateFoldLinesForMarkers(List<TextLine> allTextLines, Pen[] colors, Pen[] endMarker) { foreach (var marker in _markers) { var end = marker.FoldingSection.EndOffset; var endTextLineNr = GetTextLineIndexFromOffset(allTextLines, end); if (!marker.FoldingSection.IsFolded && endTextLineNr >= 0) { if (marker.IsPointerOver) endMarker[endTextLineNr] = _selectedFoldingControlPen; else if (endMarker[endTextLineNr] == null) endMarker[endTextLineNr] = _foldingControlPen; } var startTextLineNr = GetTextLineIndexFromOffset(allTextLines, marker.FoldingSection.StartOffset); if (startTextLineNr >= 0) { for (var i = startTextLineNr + 1; i < colors.Length && i - 1 != endTextLineNr; i++) { if (marker.IsPointerOver) colors[i] = _selectedFoldingControlPen; else if (colors[i] == null) colors[i] = _foldingControlPen; } } } } /// <summary> /// Draws the lines for the folding sections (vertical line with 'color', horizontal lines with 'endMarker') /// Each entry in the input arrays corresponds to one TextLine. /// </summary> private void DrawFoldLines(DrawingContext drawingContext, Pen[] colors, Pen[] endMarker) { // Because we are using PenLineCap.Flat (the default), for vertical lines, // Y coordinates must be on pixel boundaries, whereas the X coordinate must be in the // middle of a pixel. (and the other way round for horizontal lines) var pixelSize = PixelSnapHelpers.GetPixelSize(this); var markerXPos = PixelSnapHelpers.PixelAlign(Bounds.Width / 2, pixelSize.Width); double startY = 0; var currentPen = colors[0]; var tlNumber = 0; foreach (var vl in TextView.VisualLines) { foreach (var tl in vl.TextLines) { if (endMarker[tlNumber] != null) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); drawingContext.DrawLine(endMarker[tlNumber], new Point(markerXPos - pixelSize.Width / 2, visualPos), new Point(Bounds.Width, visualPos)); } if (colors[tlNumber + 1] != currentPen) { var visualPos = GetVisualPos(vl, tl, pixelSize.Height); if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, visualPos - pixelSize.Height / 2)); } currentPen = colors[tlNumber + 1]; startY = visualPos; } tlNumber++; } } if (currentPen != null) { drawingContext.DrawLine(currentPen, new Point(markerXPos, startY + pixelSize.Height / 2), new Point(markerXPos, Bounds.Height)); } } private double GetVisualPos(VisualLine vl, TextLine tl, double pixelHeight) { var pos = vl.GetTextLineVisualYPosition(tl, VisualYPosition.TextMiddle) - TextView.VerticalOffset; return PixelSnapHelpers.PixelAlign(pos, pixelHeight); } private int GetTextLineIndexFromOffset(List<TextLine> textLines, int offset) { var lineNumber = TextView.Document.GetLineByOffset(offset).LineNumber; var vl = TextView.GetVisualLine(lineNumber); if (vl != null) { var relOffset = offset - vl.FirstDocumentLine.Offset; var line = vl.GetTextLine(vl.GetVisualColumn(relOffset)); return textLines.IndexOf(line); } return -1; } } } <MSG> Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix Fix rendering of FoldingMarginMarkers <DFF> @@ -157,7 +157,7 @@ namespace AvaloniaEdit.Folding var xPos = (finalSize.Width - m.DesiredSize.Width) / 2; m.Arrange(new Rect(PixelSnapHelpers.Round(new Point(xPos, yPos), pixelSize), m.DesiredSize)); } - return base.ArrangeOverride(finalSize); + return finalSize; } private readonly List<FoldingMarginMarker> _markers = new List<FoldingMarginMarker>(); @@ -184,6 +184,7 @@ namespace AvaloniaEdit.Folding VisualLine = line, FoldingSection = fs }; + ((ISetLogicalParent)m).SetParent(this); _markers.Add(m); VisualChildren.Add(m);
2
Merge pull request #62 from siegfriedpammer/dev/siegfriedpammer/folding-margin-fix
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10056789
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056790
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056791
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056792
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056793
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056794
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056795
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056796
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056797
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056798
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056799
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056800
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056801
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056802
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056803
<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() { 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() { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; _lineRanges[i].Length = line.TotalLength; } } } } 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); { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; _lineRanges[lineIndex].Length = line.TotalLength; } } 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> TextMate doesn't want the line terminators <DFF> @@ -62,7 +62,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[i]; _lineRanges[i].Offset = line.Offset; - _lineRanges[i].Length = line.TotalLength; + _lineRanges[i].Length = line.Length; } } } @@ -191,7 +191,7 @@ namespace AvaloniaEdit.TextMate { var line = _document.Lines[lineIndex]; _lineRanges[lineIndex].Offset = line.Offset; - _lineRanges[lineIndex].Length = line.TotalLength; + _lineRanges[lineIndex].Length = line.Length; } }
2
TextMate doesn't want the line terminators
2
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056804
<NME> module.add.js <BEF> buster.testCase('View#add()', { "setUp": function() { this.view = new helpers.Views.List(); beforeEach(function() { viewToTest = new helpers.Views.List(); }); test("Should throw when adding undefined module", function() { var thrown; try { viewToTest.add({module: 'invalidFruit'}); } catch(e) { expect(e.message).toMatch('invalidFruit'); thrown = true; } expect(thrown).toBe(true); }); test("Should accept a View instance", function() { var pear = new helpers.Views.Pear(); viewToTest.add(pear); assert.equals(this.view.children.length, 1); }, "Should the second parameter should define the slot": function() { var apple = new Apple(); var layout = new Layout(); layout.add(apple); expect(layout.slots[1]).toBe(apple); }); test("Should aceept JSON", function() { viewToTest.add({ module: 'pear' }); expect(viewToTest.children.length).toBe(1); }); test("Should allow the second parameter to define the slot", function() { var apple = new Apple(); var layout = new Layout(); layout.add(apple, 1); expect(layout.slots[1]).toBe(apple); }); test("Should be able to define the slot in the options object", function() { var apple = new Apple(); var layout = new Layout(); layout.add(apple, { slot: 1 }); expect(layout.slots[1]).toBe(apple); }); test("Should remove a module if it already occupies this slot", function() { var apple = new Apple(); var orange = new Orange(); var layout = new Layout(); layout.add(apple, 1); expect(layout.slots[1]).toBe(apple); layout.add(orange, 1); expect(layout.slots[1]).toBe(orange); expect(layout.module('apple')).toBeUndefined(); }); test("Should remove the module if it already has parent before being added", function() { var apple = new Apple(); var layout = new Layout(); "tearDown": function() { this.view = null; } }); expect(spy).toHaveBeenCalledTimes(0); expect(layout.slots[1]).toBe(apple); layout.add(apple, 2); expect(layout.slots[1]).not.toEqual(apple); expect(layout.slots[2]).toBe(apple); expect(spy).toHaveBeenCalled(); }); afterEach(function() { helpers.destroyView(viewToTest); viewToTest = null; }); }); <MSG> Merge from master <DFF> @@ -1,4 +1,3 @@ - buster.testCase('View#add()', { "setUp": function() { this.view = new helpers.Views.List(); @@ -24,7 +23,7 @@ buster.testCase('View#add()', { assert.equals(this.view.children.length, 1); }, - "Should the second parameter should define the slot": function() { + "Should allow the second parameter to define the slot": function() { var apple = new Apple(); var layout = new Layout(); @@ -75,4 +74,4 @@ buster.testCase('View#add()', { "tearDown": function() { this.view = null; } -}); \ No newline at end of file +});
2
Merge from master
3
.js
add
mit
ftlabs/fruitmachine
10056805
<NME> index.js <BEF> /*jshint browser:true, node:true*/ 'use strict'; /** * Module Dependencies */ var util = require('utils'); var events = require('./events'); var extend = require('extend'); var mixin = util.mixin; /** * Exports */ module.exports = function(fm) { // Alias prototype for optimum // compression via uglifyjs var proto = Module.prototype; /** * Module constructor * * Options: * * - `id {String}` a unique id to query by * - `model {Object|Model}` the data with which to associate this module * - `tag {String}` tagName to use for the root element * - `classes {Array}` list of classes to add to the root element * - `template {Function}` a template to use for rendering * - `helpers {Array}`a list of helper function to use on this module * - `children {Object|Array}` list of child modules * * @constructor * @param {Object} options * @api public */ function Module(options) { // Shallow clone the options options = mixin({}, options); // Various config steps this._configure(options); this._add(options.children); // Fire before initialize event hook this.fireStatic('before initialize', options); // Run initialize hooks if (this.initialize) this.initialize(options); // Fire initialize event hook this.fireStatic('initialize', options); } /** * Configures the new Module * with the options passed * to the constructor. * * @param {Object} options * @api private */ proto._configure = function(options) { // Setup static properties this._id = options.id || util.uniqueId(); this._fmid = options.fmid || util.uniqueId('fmid'); this.tag = options.tag || this.tag || 'div'; this.classes = options.classes || this.classes || []; this.helpers = options.helpers || this.helpers || []; this.template = this._setTemplate(options.template || this.template); this.slot = options.slot; // Create id and module // lookup objects this.children = []; this._ids = {}; this._modules = {}; this.slots = {}; // Use the model passed in, // or create a model from // the data passed in. var model = options.model || options.data || {}; this.model = util.isPlainObject(model) ? new this.Model(model) : model; // Attach helpers // TODO: Fix this for non-ES5 environments this.helpers.forEach(this.attachHelper, this); // We fire and 'inflation' event here // so that helpers can make some changes // to the view before instantiation. if (options.fmid) { fm.fire('inflation', this, options); this.fireStatic('inflation', options); } }; /** * A private add method * that accepts a list of * children. * * @param {Object|Array} children * @api private */ proto._add = function(children) { if (!children) return; var isArray = util.isArray(children); var child; for (var key in children) { child = children[key]; if (!isArray) child.slot = key; this.add(child); } }, /** * Instantiates the given * helper on the Module. * * @param {Function} helper * @return {Module} * @api private */ proto.attachHelper = function(helper) { if (helper) helper(this); }, /** * Returns the template function * for the view. * * For template object like Hogan * templates with a `render` method * we need to bind the context * so they can be called without * a reciever. * * @return {Function} * @api private */ proto._setTemplate = function(fn) { return fn && fn.render ? util.bind(fn.render, fn) : fn; }; /** * Adds a child view(s) to another Module. * * Options: * * - `at` The child index at which to insert * - `inject` Injects the child's view element into the parent's * - `slot` The slot at which to insert the child * * @param {Module|Object} children * @param {Object|String|Number} options|slot */ proto.add = function(child, options) { if (!child) return this; // Options var at = options && options.at; var inject = options && options.inject; var slot = ('object' === typeof options) ? options.slot : options; // Remove this view first if it already has a parent if (child.parent) child.remove({ fromDOM: false }); // Assign a slot (prefering defined option) slot = child.slot = slot || child.slot; // Remove any module that already occupies this slot var resident = this.slots[slot]; if (resident) resident.remove({ fromDOM: false }); // If it's not a Module, make it one. if (!(child instanceof Module)) child = fm(child); util.insert(child, this.children, at); this._addLookup(child); // We append the child to the parent view if there is a view // element and the users hasn't flagged `append` false. if (inject) this._injectEl(child.el, options); // Allow chaining return this; }; /** * Removes a child view from * its current Module contexts * and also from the DOM unless * otherwise stated. * * Options: * * - `fromDOM` Whether the element should be removed from the DOM (default `true`) * * Example: * * // The following are equal * // apple is removed from the * // the view structure and DOM * layout.remove(apple); * apple.remove(); * * // Apple is removed from the * // view structure, but not the DOM * layout.remove(apple, { el: false }); * apple.remove({ el: false }); * * @return {FruitMachine} * @api public */ proto.remove = function(param1, param2) { // Don't do anything if the first arg is undefined if (arguments.length === 1 && !param1) return this; // Allow view.remove(child[, options]) // and view.remove([options]); if (param1 instanceof Module) { param1.remove(param2 || {}); return this; } // Options and aliases var options = param1 || {}; var fromDOM = options.fromDOM !== false; var parent = this.parent; var el = this.el; var parentNode = el && el.parentNode; var index; // Unless stated otherwise, // remove the view element // from its parent node. if (fromDOM && parentNode) { parentNode.removeChild(el); this._unmount(); } if (parent) { // Remove reference from views array index = parent.children.indexOf(this); parent.children.splice(index, 1); // Remove references from the lookup parent._removeLookup(this); } return this; }; /** * Creates a lookup reference for * the child view passed. * * @param {Module} child * @api private */ proto._addLookup = function(child) { var module = child.module(); // Add a lookup for module (this._modules[module] = this._modules[module] || []).push(child); // Add a lookup for id this._ids[child.id()] = child; // Store a reference by slot if (child.slot) this.slots[child.slot] = child; child.parent = this; }; /** * Removes the lookup for the * the child view passed. * * @param {Module} child * @api private */ proto._removeLookup = function(child) { var module = child.module(); // Remove the module lookup var index = this._modules[module].indexOf(child); this._modules[module].splice(index, 1); // Remove the id and slot lookup delete this._ids[child._id]; delete this.slots[child.slot]; delete child.parent; }; /** * Injects an element into the * Module's root element. * * By default the element is appended. * * Options: * * - `at` The index at which to insert. * * @param {Element} el * @param {Object} options * @api private */ proto._injectEl = function(el, options) { var at = options && options.at; var parent = this.el; if (!el || !parent) return; if (typeof at !== 'undefined') { parent.insertBefore(el, parent.children[at]); } else { parent.appendChild(el); } }; /** * Returns a decendent module * by id, or if called with no * arguments, returns this view's id. * * Example: * * myModule.id(); * //=> 'my_view_id' * * myModule.id('my_other_views_id'); * //=> Module * * @param {String|undefined} id * @return {Module|String} * @api public */ proto.id = function(id) { if (!arguments.length) return this._id; var child = this._ids[id]; if (child) return child; return this.each(function(view) { return view.id(id); }); }; /** * Returns the first descendent * Module with the passed module type. * If called with no arguments the * Module's own module type is returned. * * Example: * * // Assuming 'myModule' has 3 descendent * // views with the module type 'apple' * * myModule.modules('apple'); * //=> Module * * @param {String} key * @return {Module} */ proto.module = function(key) { if (!arguments.length) return this._module || this.name; var view = this._modules[key]; if (view && view.length) return view[0]; return this.each(function(view) { return view.module(key); }); }; /** * Returns a list of descendent * Modules that match the module * type given (Similar to * Element.querySelectorAll();). * * Example: * * // Assuming 'myModule' has 3 descendent * // views with the module type 'apple' * * myModule.modules('apple'); * //=> [ Module, Module, Module ] * * @param {String} key * @return {Array} * @api public */ proto.modules = function(key) { var list = this._modules[key] || []; // Then loop each child and run the // same opperation, appending the result // onto the list. this.each(function(view) { list = list.concat(view.modules(key)); }); return list; }; /** * Calls the passed function * for each of the view's * children. * * Example: * * myModule.each(function(child) { * // Do stuff with each child view... * }); * * @param {Function} fn * @return {[type]} */ proto.each = function(fn) { var l = this.children.length; var result; for (var i = 0; i < l; i++) { result = fn(this.children[i]); if (result) return result; } }; /** * Templates the view, including * any descendent views returning * an html string. All data in the * views model is made accessible * to the template. * * Child views are printed into the * parent template by `id`. Alternatively * children can be iterated over a a list * and printed with `{{{child}}}}`. * * Example: * * <div class="slot-1">{{{<slot>}}}</div> * <div class="slot-2">{{{<slot>}}}</div> * * // or * * {{#children}} * {{{child}}} * {{/children}} * * @return {String} * @api public */ proto.toHTML = function() { var html = this._innerHTML(); // Wrap the html in a FruitMachine // generated root element and return. return this._wrapHTML(html); }; /** * Get the view's innerHTML * * @return {String} */ proto._innerHTML = function() { this.fireStatic('before tohtml'); var data = {}; var html; var tmp; // Create an array for view // children data needed in template. data[fm.config.templateIterator] = []; // Loop each child this.each(function(child) { if (!child.model) { var err = new Error("Child without a model"); err.context = child; throw err; } tmp = {}; html = child.toHTML(); data[child.slot || child.id()] = html; tmp[fm.config.templateInstance] = html; data.children.push(mixin(tmp, child.model.toJSON())); }); // Run the template render method // passing children data (for looping // or child views) mixed with the // view's model data. return this.template ? this.template(mixin(data, this.model.toJSON())) : ''; }; /** * Wraps the module html in * a root element. * * @param {String} html * @return {String} * @api private */ proto._wrapHTML = function(html) { return '<' + this.tag + ' class="' + this._classes().join(' ') + '" id="' + this._fmid + '">' + html + '</' + this.tag + '>'; }; /** * Gets a space separated list * of all a view's classes * * @return {String} * @api private */ proto._classes = function() { return [this.module()].concat(this.classes); }; /** * Renders the view and replaces * the `view.el` with a freshly * rendered node. * * Fires a `render` event on the view. * * @return {Module} */ proto.render = function() { this.fireStatic('before render'); // If possible recycle outer element but // build from scratch if there is no // existing element or if tag changed var el = this.el; var classes; if (el && el.tagName === this.tag.toUpperCase()) { el.innerHTML = this._innerHTML(); this._unmountChildren(); classes = el.className.split(/\s+/); this._classes().forEach(function(add) { if (!~classes.indexOf(add)) el.className = el.className + ' ' + add; }); // Sets a new element as a view's // root element (purging descendent // element caches). } else { this._setEl(util.toNode(this.toHTML())); } // Fetch all child module elements this._fetchEls(this.el); // Handy hook this.fireStatic('render'); return this; }; /** * Sets up a view and all descendent * views. * * Setup will be aborted if no `view.el` * is found. If a view is already setup, * teardown is run first to prevent a * view being setup twice. * * Your custom `setup()` method is called * * Options: * * - `shallow` Does not recurse when `true` (default `false`) * * @param {Object} options * @return {Module} */ proto.setup = function(options) { var shallow = options && options.shallow; // Attempt to fetch the view's // root element. Don't continue // if no route element is found. if (!this._getEl()) 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 }); // Fire the `setup` event hook this.fireStatic('before setup'); if (this._setup) this._setup(); this.fireStatic('setup'); // Flag view as 'setup' this.isSetup = true; // Call 'setup' on all subviews // first (top down recursion) if (!shallow) { this.each(function(child) { child.setup(); }); } // For chaining return this; }; /** * Tearsdown a view and all descendent * views that have been setup. * * Your custom `teardown` method is * called and a `teardown` event is fired. * * Options: * * - `shallow` Does not recurse when `true` (default `false`) * * @param {Object} options * @return {Module} */ proto.teardown = function(options) { var shallow = options && options.shallow; // Call 'setup' on all subviews // first (bottom up recursion). if (!shallow) { this.each(function(child) { child.teardown(); }); } // Only teardown if this view // has been setup. Teardown // is supposed to undo all the // work setup does, and therefore // will likely run into undefined // variables if setup hasn't run. if (this.isSetup) { this.fireStatic('before teardown'); if (this._teardown) this._teardown(); this.fireStatic('teardown'); this.isSetup = false; } // For chaining return this; }; /** * Completely destroys a view. This means * a view is torn down, removed from it's * current layout context and removed * from the DOM. * * Your custom `destroy` method is * called and a `destroy` event is fired. * * NOTE: `.remove()` is only run on the view * that `.destroy()` is directly called on. * * Options: * * - `fromDOM` Whether the view should be removed from DOM (default `true`) * * @api public */ proto.destroy = function(options) { options = options || {}; var remove = options.remove !== false; var l = this.children.length; // Destroy each child view. // We don't waste time removing // the child elements as they will // get removed when the parent // element is removed. // // We can't use the standard Module#each() // as the array length gets altered // with each iteration, hense the // reverse while loop. while (l--) { this.children[l].destroy({ remove: false }); } // Don't continue if this view // has already been destroyed. if (this.destroyed) return this; // .remove() is only run on the view that // destroy() was called on. // // It is a waste of time to remove the // descendent views as well, as any // references to them will get wiped // within destroy and they will get // removed from the DOM with the main view. if (remove) this.remove(options); // Run teardown this.teardown({ shallow: true }); // Fire an event hook before the // custom destroy logic is run this.fireStatic('before destroy'); // If custom destroy logic has been // defined on the prototype then run it. if (this._destroy) this._destroy(); // Trigger a `destroy` event // for custom Modules to bind to. this.fireStatic('destroy'); // Unbind any old event listeners this.off(); // Set a flag to say this view // has been destroyed. This is // useful to check for after a // slow ajax call that might come // back after a view has been detroyed. this.destroyed = true; // Clear references this.el = this.model = this.parent = this._modules = this._ids = this._id = null; }; /** * Destroys all children. * * Is this needed? * * @return {Module} * @api public */ proto.empty = function() { var l = this.children.length; while (l--) this.children[l].destroy(); return this; }; /** * Fetches all descendant elements * from the given root element. * * @param {Element} root * @return {undefined} * @api private */ proto._fetchEls = function(root) { if (!root) return; this.each(function(child) { child.mount(util.byId(child._fmid, root)); child._fetchEls(child.el || root); }); }; /** * Associate the view with an element. * Provide events and lifecycle methods * to fire when the element is newly * associated. * * @param {Element} el * @return {Element} */ proto.mount = function(el) { if(this.el !== el) { this.fireStatic('before mount'); this.el = el; if(this._mount) this._mount(); this.fireStatic('mount'); } return this.el; }; /** * Recursively fire unmount events on * children. To be called when a view's * children are implicitly removed from * the DOM (e.g. setting innerHTML) * * @api private */ proto._unmountChildren = function() { this.each(function(child) { child._unmount(); }); }; /*_setEl * Recursively fire unmount events on * a view and its children. To be * called when a view'is implicitly * removed from the DOM (e.g. _setEl) * * @api private */ proto._unmount = function() { this._unmountChildren(); this.fireStatic('unmount'); } /** * Returns the Module's root element. * * If a cache is present it is used, * else we search the DOM, else we * find the closest element and * perform a querySelector using * the view._fmid. * * @return {Element|undefined} * @api private */ proto._getEl = function() { if (!util.hasDom()) return; return this.mount(this.el || document.getElementById(this._fmid)); }; /** * Sets a root element on a view. * If the view already has a root * element, it is replaced. * * IMPORTANT: All descendent root * element caches are purged so that * the new correct elements are retrieved * next time Module#getElement is called. * * @param {Element} el * @return {Module} * @api private */ proto._setEl = function(el) { var existing = this.el; var parentNode = existing && existing.parentNode; // If the existing element has a context, replace it if (parentNode) { parentNode.replaceChild(el, existing); this._unmount(); } // Update cache this.mount(el); return this; }; /** * Empties the destination element * and appends the view into it. * * @param {Element} dest * @return {Module} * @api public */ proto.inject = function(dest) { if (dest) { dest.innerHTML = ''; this.insertBefore(dest, null); this.fireStatic('inject'); } return this; }; /** * Appends the view element into * the destination element. * * @param {Element} dest * @return {Module} * @api public */ proto.appendTo = function(dest) { return this.insertBefore(dest, null); }; /** * Inserts the view element before the * given child of the destination element. * * @param {Element} dest * @param {Element} beforeEl * @return {Module} * @api public */ proto.insertBefore = function(dest, beforeEl) { if (this.el && dest && dest.insertBefore) { dest.insertBefore(this.el, beforeEl); // This badly-named event is for legacy reasons; perhaps 'insert' would be better here? this.fireStatic('appendto'); } return this; }; /** * Returns a JSON represention of * a FruitMachine Module. This can * be generated serverside and * passed into new FruitMachine(json) * to inflate serverside rendered * views. * * @return {Object} * @api public */ proto.toJSON = function() { var json = {}; json.children = []; // Recurse this.each(function(child) { json.children.push(child.toJSON()); }); json.id = this.id(); json.fmid = this._fmid; json.module = this.module(); json.model = this.model.toJSON(); json.slot = this.slot; // Fire a hook to allow third // parties to alter the json output this.fireStatic('tojson', json); return json; }; // Events proto.on = events.on; proto.off = events.off; proto.fire = events.fire; proto.fireStatic = events.fireStatic; // Allow Modules to be extended Module.extend = extend(util.keys(proto)); // Adding proto.Model after // Module.extend means this // key can be overwritten. proto.Model = fm.Model; return Module; }; <MSG> ensure we don't accidentally mount on null <DFF> @@ -850,7 +850,7 @@ module.exports = function(fm) { */ proto._getEl = function() { if (!util.hasDom()) return; - return this.mount(this.el || document.getElementById(this._fmid)); + return this.mount(this.el || document.getElementById(this._fmid) || undefined); }; /**
1
ensure we don't accidentally mount on null
1
.js
js
mit
ftlabs/fruitmachine
10056806
<NME> PassportServiceProvider.php <BEF> <?php namespace Dusterio\LumenPassport; use Dusterio\LumenPassport\Console\Commands\Purge; use Illuminate\Support\ServiceProvider; use Illuminate\Database\Connection; /** * Class CustomQueueServiceProvider * @package App\Providers */ class PassportServiceProvider extends ServiceProvider { /** * Bootstrap any application services. * * @return void */ public function boot() { $this->app->singleton(Connection::class, function() { return $this->app['db.connection']; }); if ($this->app->runningInConsole()) { $this->commands([ Purge::class ]); } } /** * @return void */ public function register() { } } <MSG> r 5.6 fix <DFF> @@ -23,6 +23,12 @@ class PassportServiceProvider extends ServiceProvider return $this->app['db.connection']; }); + if (preg_match('/5\.6\.\d+/', $this->app->version())) { + $this->app->singleton(\Illuminate\Hashing\HashManager::class, function ($app) { + return new \Illuminate\Hashing\HashManager($app); + }); + } + if ($this->app->runningInConsole()) { $this->commands([ Purge::class
6
r 5.6 fix
0
.php
php
mit
dusterio/lumen-passport
10056807
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple but powerful dependency management system that lets you fetch files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code in your &lt;html&gt; and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent <a href="https://github.com/ded/script.js">$script</a> library by <a href="https://github.com/ded">Dustin Diaz</a>. We kept the behavior of the library the same but we re-wrote the code from scratch to add support for error callbacks and to optimize the library for modern browsers. Currently, LoadJS is 590 bytes (minified + gzipped). The latest version of LoadJS can be found in the `dist/` directory in this repository: * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) You can also use more advanced syntax for more options: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags) ## Documentation 1. Load a single file ```javascript loadjs('/path/to/foo.js', function() { /* foo.js loaded */ }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` 1. Fetch JavaScript, CSS and image files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -11,7 +11,19 @@ LoadJS is a tiny async loader for modern browsers (590 bytes). LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple but powerful dependency management system that lets you fetch files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code in your &lt;html&gt; and then use the `loadjs` global to manage JavaScript dependencies after pageload. -LoadJS is based on the excellent <a href="https://github.com/ded/script.js">$script</a> library by <a href="https://github.com/ded">Dustin Diaz</a>. We kept the behavior of the library the same but we re-wrote the code from scratch to add support for error callbacks and to optimize the library for modern browsers. Currently, LoadJS is 590 bytes (minified + gzipped). +LoadJS is based on the excellent <a href="https://github.com/ded/script.js">$script</a> library by <a href="https://github.com/ded">Dustin Diaz</a>. We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/failure callbacks and to optimize the library for modern browsers. Currently, LoadJS is 590 bytes (minified + gzipped). + +Here's an example of what you can do with LoadJS: + +```javascript +// define a dependency bundle +loadjs(['foo.js', 'bar.js'], 'foobar'); + +// execute code elsewhere when the bundle has loaded +loadjs.ready('foobar', function() { + // foo.js & bar.js loaded +}); +``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js)
13
Update README.md
1
.md
md
mit
muicss/loadjs
10056808
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="250px"> LoadJS is a tiny async loader for modern browsers (899 bytes). [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![devDependency Status](https://david-dm.org/muicss/loadjs/dev-status.svg)](https://david-dm.org/muicss/loadjs?type=dev) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple but powerful dependency management system that lets you fetch files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code in your &lt;html&gt; and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent <a href="https://github.com/ded/script.js">$script</a> library by <a href="https://github.com/ded">Dustin Diaz</a>. We kept the behavior of the library the same but we re-wrote the code from scratch to add support for error callbacks and to optimize the library for modern browsers. Currently, LoadJS is 590 bytes (minified + gzipped). The latest version of LoadJS can be found in the `dist/` directory in this repository: * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js) You can also use more advanced syntax for more options: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags) ## Documentation 1. Load a single file ```javascript loadjs('/path/to/foo.js', function() { /* foo.js loaded */ }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], function() { /* foo.js and bar.js loaded */ }); ``` 1. Fetch JavaScript, CSS and image files ```javascript loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ ├── dist │   ├── loadjs.js │   ├── loadjs.min.js │   └── loadjs.umd.js ├── examples ├── gulpfile.js ├── LICENSE.txt ├── package.json ├── README.md ├── src │   └── loadjs.js ├── test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -11,7 +11,19 @@ LoadJS is a tiny async loader for modern browsers (590 bytes). LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple but powerful dependency management system that lets you fetch files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code in your &lt;html&gt; and then use the `loadjs` global to manage JavaScript dependencies after pageload. -LoadJS is based on the excellent <a href="https://github.com/ded/script.js">$script</a> library by <a href="https://github.com/ded">Dustin Diaz</a>. We kept the behavior of the library the same but we re-wrote the code from scratch to add support for error callbacks and to optimize the library for modern browsers. Currently, LoadJS is 590 bytes (minified + gzipped). +LoadJS is based on the excellent <a href="https://github.com/ded/script.js">$script</a> library by <a href="https://github.com/ded">Dustin Diaz</a>. We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/failure callbacks and to optimize the library for modern browsers. Currently, LoadJS is 590 bytes (minified + gzipped). + +Here's an example of what you can do with LoadJS: + +```javascript +// define a dependency bundle +loadjs(['foo.js', 'bar.js'], 'foobar'); + +// execute code elsewhere when the bundle has loaded +loadjs.ready('foobar', function() { + // foo.js & bar.js loaded +}); +``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.js)
13
Update README.md
1
.md
md
mit
muicss/loadjs
10056809
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056810
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056811
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056812
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056813
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056814
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056815
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056816
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056817
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056818
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056819
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056820
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056821
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056822
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056823
<NME> TextEditorModelTests.cs <BEF> using AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("", textEditorModel.GetLineText(0)); } } } public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Added two more unit tests <DFF> @@ -237,5 +237,43 @@ namespace AvaloniaEdit.Tests.TextMate Assert.AreEqual("", textEditorModel.GetLineText(0)); } + + [Test] + public void Remove_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = string.Empty; + Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); + Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); + } + + [Test] + public void Replace_Document_Text_Should_Update_Line_Contents() + { + TextView textView = new TextView(); + TextDocument document = new TextDocument(); + + TextEditorModel textEditorModel = new TextEditorModel( + textView, document, null); + + document.Text = "puppy\npussy\nbirdie"; + Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); + + document.Text = "one\ntwo\nthree\nfour"; + Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); + + Assert.AreEqual("one", textEditorModel.GetLineText(0)); + Assert.AreEqual("two", textEditorModel.GetLineText(1)); + Assert.AreEqual("three", textEditorModel.GetLineText(2)); + Assert.AreEqual("four", textEditorModel.GetLineText(3)); + } } }
38
Added two more unit tests
0
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10056824
<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 a module var apple = new Apple(); // Render it apple.render(); apple.el.outerHTML; //=> <div class="apple">hello</div> ``` ## Installation ``` $ npm install fruitmachine ``` or ``` $ bower install fruitmachine ``` or 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 ## 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> Remove built javascript from repo to avoid it getting out of date; link to Browserify CDN for built version <DFF> @@ -35,10 +35,9 @@ $ bower install fruitmachine or -Download the [production version][min] (~2k gzipped) or the [development version][max]. +Download the [pre-build version][built] (~2k gzipped). -[min]: http://github.com/ftlabs/fruitmachine/raw/master/build/fruitmachine.min.js -[max]: http://github.com/ftlabs/fruitmachine/raw/master/build/fruitmachine.js +[built]: http://wzrd.in/standalone/fruitmachine@latest ## Examples
2
Remove built javascript from repo to avoid it getting out of date; link to Browserify CDN for built version
3
.md
md
mit
ftlabs/fruitmachine
10056825
<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 a module var apple = new Apple(); // Render it apple.render(); apple.el.outerHTML; //=> <div class="apple">hello</div> ``` ## Installation ``` $ npm install fruitmachine ``` or ``` $ bower install fruitmachine ``` or Download the [pre-built version][built] (~2k gzipped). [built]: http://wzrd.in/standalone/fruitmachine@latest ## 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 ``` 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> Docs changes <DFF> @@ -80,7 +80,7 @@ $ npm test $ node_modules/.bin/buster-static ``` -Visit http://localhost:8282/ in browser +...then isit http://localhost:8282/ in browser ## Author
1
Docs changes
1
.md
md
mit
ftlabs/fruitmachine
10056826
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056827
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056828
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056829
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056830
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056831
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056832
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056833
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056834
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056835
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056836
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056837
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056838
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056839
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056840
<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() { 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--) { 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; _documentSnapshot.Update(e); // invalidate the changed line it's previous line // some grammars (JSON, csharp, ...) // need to invalidate the previous line if (startLine - 1 >= 0) InvalidateLine(startLine - 1); InvalidateLine(startLine); } catch (Exception ex) { // 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> Use the new API InvalidateLineRange when invalidating two lines <DFF> @@ -121,12 +121,15 @@ namespace AvaloniaEdit.TextMate _documentSnapshot.Update(e); - // invalidate the changed line it's previous line + if (startLine == 0) + { + InvalidateLine(startLine); + return; + } + // some grammars (JSON, csharp, ...) - // need to invalidate the previous line - if (startLine - 1 >= 0) - InvalidateLine(startLine - 1); - InvalidateLine(startLine); + // need to invalidate the previous line too + InvalidateLineRange(startLine - 1, startLine); } catch (Exception ex) {
8
Use the new API InvalidateLineRange when invalidating two lines
5
.cs
TextMate/TextEditorModel
mit
AvaloniaUI/AvaloniaEdit
10056841
<NME> text.log <BEF> 03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** 03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf 03/22 08:51:01 INFO :.main: Using log level 511 03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. 03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS 03/22 08:51:02 INFO :..reg_process: registering process with the system 03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration 03/22 08:51:02 INFO :..reg_process: return from registration rc=0 03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and <MSG> Add a stack trace to visualize an italic text example in the log file, for the demo application <DFF> @@ -14,6 +14,43 @@ 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** +03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf +03/22 08:51:01 INFO :.main: Using log level 511 +03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. +03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS +03/22 08:51:02 INFO :..reg_process: registering process with the system +03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration +03/22 08:51:02 INFO :..reg_process: return from registration rc=0 +03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 +03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 +03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 +03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 +03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 +03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 +03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 +03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:06 ERROR :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes, something went wrong + at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18 + at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23 + at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13 +03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer +03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
37
Add a stack trace to visualize an italic text example in the log file, for the demo application
0
.log
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10056842
<NME> text.log <BEF> 03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** 03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf 03/22 08:51:01 INFO :.main: Using log level 511 03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. 03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS 03/22 08:51:02 INFO :..reg_process: registering process with the system 03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration 03/22 08:51:02 INFO :..reg_process: return from registration rc=0 03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and <MSG> Add a stack trace to visualize an italic text example in the log file, for the demo application <DFF> @@ -14,6 +14,43 @@ 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** +03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf +03/22 08:51:01 INFO :.main: Using log level 511 +03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. +03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS +03/22 08:51:02 INFO :..reg_process: registering process with the system +03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration +03/22 08:51:02 INFO :..reg_process: return from registration rc=0 +03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 +03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 +03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 +03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 +03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 +03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 +03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 +03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:06 ERROR :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes, something went wrong + at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18 + at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23 + at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13 +03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer +03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
37
Add a stack trace to visualize an italic text example in the log file, for the demo application
0
.log
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10056843
<NME> text.log <BEF> 03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** 03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf 03/22 08:51:01 INFO :.main: Using log level 511 03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. 03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS 03/22 08:51:02 INFO :..reg_process: registering process with the system 03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration 03/22 08:51:02 INFO :..reg_process: return from registration rc=0 03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and <MSG> Add a stack trace to visualize an italic text example in the log file, for the demo application <DFF> @@ -14,6 +14,43 @@ 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** +03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf +03/22 08:51:01 INFO :.main: Using log level 511 +03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. +03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS +03/22 08:51:02 INFO :..reg_process: registering process with the system +03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration +03/22 08:51:02 INFO :..reg_process: return from registration rc=0 +03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 +03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 +03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 +03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 +03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 +03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 +03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 +03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:06 ERROR :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes, something went wrong + at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18 + at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23 + at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13 +03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer +03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
37
Add a stack trace to visualize an italic text example in the log file, for the demo application
0
.log
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10056844
<NME> text.log <BEF> 03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** 03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf 03/22 08:51:01 INFO :.main: Using log level 511 03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. 03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS 03/22 08:51:02 INFO :..reg_process: registering process with the system 03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration 03/22 08:51:02 INFO :..reg_process: return from registration rc=0 03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and <MSG> Add a stack trace to visualize an italic text example in the log file, for the demo application <DFF> @@ -14,6 +14,43 @@ 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** +03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf +03/22 08:51:01 INFO :.main: Using log level 511 +03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. +03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS +03/22 08:51:02 INFO :..reg_process: registering process with the system +03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration +03/22 08:51:02 INFO :..reg_process: return from registration rc=0 +03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 +03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 +03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 +03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 +03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 +03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 +03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 +03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:06 ERROR :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes, something went wrong + at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18 + at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23 + at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13 +03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer +03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
37
Add a stack trace to visualize an italic text example in the log file, for the demo application
0
.log
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10056845
<NME> text.log <BEF> 03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** 03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf 03/22 08:51:01 INFO :.main: Using log level 511 03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. 03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS 03/22 08:51:02 INFO :..reg_process: registering process with the system 03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration 03/22 08:51:02 INFO :..reg_process: return from registration rc=0 03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and <MSG> Add a stack trace to visualize an italic text example in the log file, for the demo application <DFF> @@ -14,6 +14,43 @@ 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** +03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf +03/22 08:51:01 INFO :.main: Using log level 511 +03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. +03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS +03/22 08:51:02 INFO :..reg_process: registering process with the system +03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration +03/22 08:51:02 INFO :..reg_process: return from registration rc=0 +03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 +03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 +03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 +03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 +03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 +03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 +03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 +03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:06 ERROR :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes, something went wrong + at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18 + at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23 + at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13 +03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer +03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
37
Add a stack trace to visualize an italic text example in the log file, for the demo application
0
.log
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10056846
<NME> text.log <BEF> 03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** 03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf 03/22 08:51:01 INFO :.main: Using log level 511 03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. 03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS 03/22 08:51:02 INFO :..reg_process: registering process with the system 03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration 03/22 08:51:02 INFO :..reg_process: return from registration rc=0 03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and <MSG> Add a stack trace to visualize an italic text example in the log file, for the demo application <DFF> @@ -14,6 +14,43 @@ 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** +03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf +03/22 08:51:01 INFO :.main: Using log level 511 +03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. +03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS +03/22 08:51:02 INFO :..reg_process: registering process with the system +03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration +03/22 08:51:02 INFO :..reg_process: return from registration rc=0 +03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 +03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 +03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 +03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 +03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 +03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 +03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 +03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:06 ERROR :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes, something went wrong + at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18 + at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23 + at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13 +03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer +03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
37
Add a stack trace to visualize an italic text example in the log file, for the demo application
0
.log
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10056847
<NME> text.log <BEF> 03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** 03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf 03/22 08:51:01 INFO :.main: Using log level 511 03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. 03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS 03/22 08:51:02 INFO :..reg_process: registering process with the system 03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration 03/22 08:51:02 INFO :..reg_process: return from registration rc=0 03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and <MSG> Add a stack trace to visualize an italic text example in the log file, for the demo application <DFF> @@ -14,6 +14,43 @@ 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** +03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf +03/22 08:51:01 INFO :.main: Using log level 511 +03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. +03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS +03/22 08:51:02 INFO :..reg_process: registering process with the system +03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration +03/22 08:51:02 INFO :..reg_process: return from registration rc=0 +03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 +03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 +03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 +03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 +03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 +03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 +03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 +03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:06 ERROR :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes, something went wrong + at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18 + at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23 + at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13 +03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer +03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
37
Add a stack trace to visualize an italic text example in the log file, for the demo application
0
.log
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10056848
<NME> text.log <BEF> 03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** 03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf 03/22 08:51:01 INFO :.main: Using log level 511 03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. 03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS 03/22 08:51:02 INFO :..reg_process: registering process with the system 03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration 03/22 08:51:02 INFO :..reg_process: return from registration rc=0 03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and <MSG> Add a stack trace to visualize an italic text example in the log file, for the demo application <DFF> @@ -14,6 +14,43 @@ 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** +03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf +03/22 08:51:01 INFO :.main: Using log level 511 +03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. +03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS +03/22 08:51:02 INFO :..reg_process: registering process with the system +03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration +03/22 08:51:02 INFO :..reg_process: return from registration rc=0 +03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 +03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 +03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 +03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 +03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 +03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 +03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 +03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:06 ERROR :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes, something went wrong + at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18 + at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23 + at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13 +03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer +03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
37
Add a stack trace to visualize an italic text example in the log file, for the demo application
0
.log
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit
10056849
<NME> text.log <BEF> 03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** 03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf 03/22 08:51:01 INFO :.main: Using log level 511 03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. 03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS 03/22 08:51:02 INFO :..reg_process: registering process with the system 03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration 03/22 08:51:02 INFO :..reg_process: return from registration rc=0 03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP 03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. 03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp 03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and <MSG> Add a stack trace to visualize an italic text example in the log file, for the demo application <DFF> @@ -14,6 +14,43 @@ 03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:01 INFO :.main: *************** RSVP Agent started *************** +03/22 08:51:01 INFO :...locate_configFile: Specified configuration file: /u/user10/rsvpd1.conf +03/22 08:51:01 INFO :.main: Using log level 511 +03/22 08:51:01 INFO :..settcpimage: Get TCP images rc - EDC8112I Operation not supported on socket. +03/22 08:51:01 INFO :..settcpimage: Associate with TCP/IP image name = TCPCS +03/22 08:51:02 INFO :..reg_process: registering process with the system +03/22 08:51:02 INFO :..reg_process: attempt OS/390 registration +03/22 08:51:02 INFO :..reg_process: return from registration rc=0 +03/22 08:51:06 TRACE :...read_physical_netif: Home list entries returned = 7 +03/22 08:51:06 INFO :...read_physical_netif: index #0, interface VLINK1 has address 129.1.1.1, ifidx 0 +03/22 08:51:06 INFO :...read_physical_netif: index #1, interface TR1 has address 9.37.65.139, ifidx 1 +03/22 08:51:06 INFO :...read_physical_netif: index #2, interface LINK11 has address 9.67.100.1, ifidx 2 +03/22 08:51:06 INFO :...read_physical_netif: index #3, interface LINK12 has address 9.67.101.1, ifidx 3 +03/22 08:51:06 INFO :...read_physical_netif: index #4, interface CTCD0 has address 9.67.116.98, ifidx 4 +03/22 08:51:06 INFO :...read_physical_netif: index #5, interface CTCD2 has address 9.67.117.98, ifidx 5 +03/22 08:51:06 INFO :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +03/22 08:51:06 ERROR :...read_physical_netif: index #6, interface LOOPBACK has address 127.0.0.1, ifidx 0 +ConsoleApplication1.MyCustomException: some message .... ---> System.Exception: Oh noes, something went wrong + at ConsoleApplication1.SomeObject.OtherMethod() in C:\ConsoleApplication1\SomeObject.cs:line 24 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 14 + at ConsoleApplication1.SomeObject..ctor() in C:\ConsoleApplication1\SomeObject.cs:line 18 + at ConsoleApplication1.Program.DoSomething() in C:\ConsoleApplication1\Program.cs:line 23 + at ConsoleApplication1.Program.Main(String[] args) in C:\ConsoleApplication1\Program.cs:line 13 +03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer +03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 129.1.1.1, entity for rsvp allocated and initialized +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp +03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP via UDP +03/22 08:51:06 WARNING:.....mailslot_create: setsockopt(MCAST_ADD) failed - EDC8116I Address not available. +03/22 08:51:06 INFO :....mailbox_register: mailbox allocated for rsvp-udp +03/22 08:51:06 TRACE :..entity_initialize: interface 9.37.65.139, entity for rsvp allocated and 03/22 08:51:06 INFO :....mailslot_create: creating mailslot for timer 03/22 08:51:06 INFO :...mailbox_register: mailbox allocated for timer 03/22 08:51:06 INFO :.....mailslot_create: creating mailslot for RSVP
37
Add a stack trace to visualize an italic text example in the log file, for the demo application
0
.log
Demo/Resources/SampleFiles/text
mit
AvaloniaUI/AvaloniaEdit