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
|
---|---|---|---|---|---|---|---|---|
10067850 | <NME> SearchPanel.xaml
<BEF> <Styles xmlns="https://github.com/avaloniaui"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:ae="clr-namespace:AvaloniaEdit;assembly=AvaloniaEdit"
xmlns:search="clr-namespace:AvaloniaEdit.Search;assembly=AvaloniaEdit">
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle">
<Setter Property="Template">
<ControlTemplate>
<Path Fill="{DynamicResource ThemeForegroundBrush}"
VerticalAlignment="Center"
HorizontalAlignment="Center"
Data="M 0 2 L 4 6 L 0 10 Z" />
</ControlTemplate>
</Setter>
</Style>
<Style Selector="search|SearchPanel ToggleButton.ExpanderToggle:checked /template/ Path">
<Setter Property="RenderTransform">
<RotateTransform Angle="90" />
</Setter>
</Style>
<Style Selector="search|SearchPanel Button">
<Setter Property="BorderThickness" Value="0"/>
<Setter Property="Background" Value="Transparent"/>
</Style>
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
Value="1" />
<Setter Property="BorderBrush"
Value="{DynamicResource ThemeBorderLowBrush}" />
<Setter Property="Background"
Value="{DynamicResource ThemeControlLowBrush}" />
<Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border Name="PART_Border" BorderThickness="{TemplateBinding BorderThickness}"
BorderBrush="{TemplateBinding BorderBrush}"
Background="{TemplateBinding Background}"
HorizontalAlignment="Right"
VerticalAlignment="Top" TextElement.FontFamily="Segoi UI" TextElement.FontSize="10">
<Grid ColumnDefinitions="Auto,Auto,Auto"
RowDefinitions="Auto,Auto">
<Popup Name="PART_MessageView"
Classes="ToolTip"
PlacementMode="Bottom"
IsLightDismissEnabled="False"
Focusable="False"
IsOpen="False">
<ContentPresenter Name="PART_MessageContent" />
</Popup>
<ToggleButton Classes="ExpanderToggle" Name="Expander" VerticalAlignment="Top" IsVisible="{Binding !_textEditor.IsReadOnly, RelativeSource={RelativeSource TemplatedParent}}"
IsChecked="{Binding IsReplaceMode, Mode=TwoWay, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="0"
Grid.Row="0"
Width="16"
Margin="2">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchToggleReplace}" />
</ToolTip.Tip>
</ToggleButton>
<StackPanel Grid.Column="1">
<StackPanel Orientation="Horizontal"
Grid.Column="2"
Grid.Row="0">
<TextBox Watermark="{x:Static ae:SR.SearchLabel}"
Name="PART_searchTextBox"
Grid.Column="1"
Grid.Row="0"
Width="150"
Height="24"
Margin="3,3,3,0"
Text="{Binding SearchPattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindPrevious}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindPreviousText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindPrevious.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.FindNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchFindNextText}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.FindNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Height="16" Background="Transparent" BorderThickness="0"
Width="16"
HorizontalAlignment="Right"
VerticalAlignment="Top"
Command="{x:Static search:SearchCommands.CloseSearchPanel}"
VerticalContentAlignment="Center"
HorizontalContentAlignment="Center"
Focusable="True">
<Path Data="M 0,0 L 8,8 M 8,0 L 0,8"
Stroke="{DynamicResource ThemeForegroundBrush}"
StrokeThickness="1" />
</Button>
</StackPanel>
<StackPanel Name="ReplaceButtons" IsVisible="{Binding #Expander.IsChecked}"
Orientation="Horizontal"
Grid.Column="2"
Grid.Row="1">
<TextBox Name="ReplaceBox" Watermark="{x:Static ae:SR.ReplaceLabel}"
IsVisible="{Binding IsReplaceMode, RelativeSource={RelativeSource TemplatedParent}}"
Grid.Column="1"
Grid.Row="1"
Width="150"
Height="24"
Margin="3 3 3 0"
Text="{Binding ReplacePattern, RelativeSource={RelativeSource TemplatedParent}}" />
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceNext}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceNext}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceNext.png?assembly=AvaloniaEdit" />
</Button>
<Button Margin="3"
Height="24"
Width="24"
Command="{x:Static search:SearchCommands.ReplaceAll}">
<ToolTip.Tip>
<TextBlock Text="{x:Static ae:SR.SearchReplaceAll}" />
</ToolTip.Tip>
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.ReplaceAll.png?assembly=AvaloniaEdit" />
</Button>
</StackPanel>
<StackPanel Orientation="Horizontal">
<ToggleButton IsChecked="{Binding MatchCase, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchCaseText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CaseSensitive.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding WholeWords, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchMatchWholeWordsText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.CompleteWord.png?assembly=AvaloniaEdit" />
</ToggleButton>
<ToggleButton IsChecked="{Binding UseRegex, RelativeSource={RelativeSource TemplatedParent}}" ToolTip.Tip="{x:Static ae:SR.SearchUseRegexText}" Margin="3"
Height="24"
Width="24">
<Image Width="16"
Height="16"
Stretch="Fill"
Source="resm:AvaloniaEdit.Search.Assets.RegularExpression.png?assembly=AvaloniaEdit" />
</ToggleButton>
</StackPanel>
</StackPanel>
</Grid>
</Border>
</ControlTemplate>
</Setter>
</Style>
</Styles>
<MSG> fix focusing of search panel
<DFF> @@ -28,6 +28,7 @@
Value="DarkGray" />
<Setter Property="Background"
Value="#eeeeee" />
+ <Setter Property="Focusable" Value="True" />
<Setter Property="Template">
<ControlTemplate>
<Border BorderThickness="{TemplateBinding BorderThickness}"
| 1 | fix focusing of search panel | 0 | .xaml | xaml | mit | AvaloniaUI/AvaloniaEdit |
10067851 | <NME> module.on.js
<BEF>
describe('View#on()', function() {
var viewToTest;
beforeEach(function() {
viewToTest = helpers.createView();
this.view.on('testevent', spy);
this.view.fire('testevent');
assert(spy.called);
},
"Should recieve the callback when event is fired on a sub view": function() {
expect(spy).toHaveBeenCalled();
});
this.view.on('testevent', spy);
apple.fire('testevent');
assert(spy.called);
},
"Should *not* recieve the callback when event is fired on a sub view that *doesn't* match the target": function() {
expect(spy).toHaveBeenCalled();
});
this.view.on('testevent', 'orange', spy);
apple.fire('testevent');
refute(spy.called);
},
"Should receive the callback when event is fired on a sub view that *does* match the target": function() {
expect(spy).not.toHaveBeenCalled();
});
this.view.on('testevent', 'apple', spy);
apple.fire('testevent');
assert(spy.called);
},
"Should pass the correct arguments to delegate event listeners": function() {
expect(spy).toHaveBeenCalled();
});
this.view.on('testevent', 'apple', spy);
apple.fire('testevent', 'foo', 'bar');
assert(spy.calledWith('foo', 'bar'));
},
tearDown: helpers.destroyView
});
});
test("#off without a module should also unbind listeners, regardless of how they are bound", function() {
var spy = jest.fn();
var apple = viewToTest.module('apple');
viewToTest.on('testevent', 'apple', spy);
apple.fire('testevent');
expect(spy).toHaveBeenCalled();
spy.mockClear();
viewToTest.off('testevent', spy);
apple.fire('testevent');
expect(spy).not.toHaveBeenCalled();
});
afterEach(function() {
helpers.destroyView();
viewToTest = null;
});
});
<MSG> Merge pull request #74 from ftlabs/off
Add ability to unbind event listener if initially bound with module name - fixes #73
<DFF> @@ -7,7 +7,7 @@ buster.testCase('View#on()', {
this.view.on('testevent', spy);
this.view.fire('testevent');
- assert(spy.called);
+ assert(spy.called);
},
"Should recieve the callback when event is fired on a sub view": function() {
@@ -16,7 +16,7 @@ buster.testCase('View#on()', {
this.view.on('testevent', spy);
apple.fire('testevent');
- assert(spy.called);
+ assert(spy.called);
},
"Should *not* recieve the callback when event is fired on a sub view that *doesn't* match the target": function() {
@@ -25,7 +25,7 @@ buster.testCase('View#on()', {
this.view.on('testevent', 'orange', spy);
apple.fire('testevent');
- refute(spy.called);
+ refute(spy.called);
},
"Should receive the callback when event is fired on a sub view that *does* match the target": function() {
@@ -34,7 +34,7 @@ buster.testCase('View#on()', {
this.view.on('testevent', 'apple', spy);
apple.fire('testevent');
- assert(spy.called);
+ assert(spy.called);
},
"Should pass the correct arguments to delegate event listeners": function() {
@@ -43,8 +43,41 @@ buster.testCase('View#on()', {
this.view.on('testevent', 'apple', spy);
apple.fire('testevent', 'foo', 'bar');
- assert(spy.calledWith('foo', 'bar'));
+ assert(spy.calledWith('foo', 'bar'));
+ },
+
+ "Should be able to unbind event listeners if initially bound with module name": function() {
+ var spy = this.spy();
+ var apple = this.view.module('apple');
+
+ this.view.on('testevent', 'apple', spy);
+ apple.fire('testevent');
+ assert(spy.called);
+
+ spy.reset();
+ this.view.off('testevent', 'apple', spy);
+ apple.fire('testevent', 'foo', 'bar');
+ refute(spy.called);
+ },
+
+ "#off with module will unbind all matching listeners, regardless of how they are bound": function() {
+ var spy = this.spy();
+ var spy2 = this.spy();
+ var apple = this.view.module('apple');
+
+ this.view.on('testevent', 'apple', spy);
+ this.view.on('testevent', spy2);
+ apple.fire('testevent');
+ assert(spy.called);
+ assert(spy2.called);
+
+ spy.reset();
+ spy2.reset();
+ this.view.off('testevent', 'apple');
+ apple.fire('testevent');
+ refute(spy.called);
+ assert(spy2.called);
},
tearDown: helpers.destroyView
-});
\ No newline at end of file
+});
| 39 | Merge pull request #74 from ftlabs/off | 6 | .js | on | mit | ftlabs/fruitmachine |
10067852 | <NME> README.md <BEF> # jsGrid Lightweight Grid jQuery Plugin [](https://travis-ci.org/tabalinas/jsgrid) Project site [js-grid.com](http://js-grid.com/) **jsGrid** is a lightweight client-side data grid control based on jQuery. It supports basic grid operations like inserting, filtering, editing, deleting, paging, sorting, and validating. jsGrid is tunable and allows to customize appearance and components.  ## Table of contents * [Demos](#demos) * [Installation](#installation) * [Basic Usage](#basic-usage) * [Configuration](#configuration) * [Grid Fields](#grid-fields) * [Methods](#methods) * [Callbacks](#callbacks) * [Grid Controller](#grid-controller) * [Validation](#validation) * [Localization](#localization) * [Sorting Strategies](#sorting-strategies) * [Load Strategies](#load-strategies) * [Load Indication](#load-indication) * [Requirement](#requirement) * [Compatibility](#compatibility) ## Demos See [Demos](http://js-grid.com/demos/) on project site. Sample projects showing how to use jsGrid with the most popular backend technologies * **PHP** - https://github.com/tabalinas/jsgrid-php * **ASP.NET WebAPI** - https://github.com/tabalinas/jsgrid-webapi * **Express (NodeJS)** - https://github.com/tabalinas/jsgrid-express * **Ruby on Rail** - https://github.com/tabalinas/jsgrid-rails * **Django (Python)** - https://github.com/tabalinas/jsgrid-django ## Installation Install jsgrid with bower: ```bash $ bower install js-grid --save ``` Find jsGrid cdn links [here](https://cdnjs.com/libraries/jsgrid). ## Basic Usage Ensure that jQuery library of version 1.8.3 or later is included. Include `jsgrid.min.js`, `jsgrid-theme.min.css`, and `jsgrid.min.css` files into the web page. Create grid applying jQuery plugin `jsGrid` with grid config as follows: ```javascript $("#jsGrid").jsGrid({ width: "100%", height: "400px", filtering: true, editing: true, sorting: true, paging: true, data: db.clients, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] }); ``` ## Configuration The config object may contain following options (default values are specified below): ```javascript { fields: [], data: [], autoload: false, controller: { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, width: "auto", height: "auto", heading: true, filtering: false, inserting: false, editing: false, selecting: true, sorting: false, paging: false, pageLoading: false, insertRowLocation: "bottom", rowClass: function(item, itemIndex) { ... }, rowClick: function(args) { ... }, rowDoubleClick: function(args) { ... }, noDataContent: "Not found", confirmDeleting: true, deleteConfirm: "Are you sure?", pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", invalidNotify: function(args) { ... } invalidMessage: "Invalid data entered!", loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, loadIndicator: function(config) { ... } loadStrategy: function(config) { ... } updateOnResize: true, rowRenderer: null, headerRowRenderer: null, filterRowRenderer: null, insertRowRenderer: null, editRowRenderer: null, pagerRenderer: null } ``` ### fields An array of fields (columns) of the grid. Each field has general options and specific options depending on field type. General options peculiar to all field types: ```javascript { type: "", name: "", title: "", align: "", width: 100, visible: true, css: "", headercss: "", filtercss: "", insertcss: "", editcss: "", filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", headerTemplate: function() { ... }, itemTemplate: function(value, item) { ... }, filterTemplate: function() { ... }, insertTemplate: function() { ... }, editTemplate: function(value, item) { ... }, filterValue: function() { ... }, insertValue: function() { ... }, editValue: function() { ... }, cellRenderer: null, validate: null } ``` - **type** is a string key of field (`"text"|"number"|"checkbox"|"select"|"textarea"|"control"`) in fields registry `jsGrid.fields` (the registry can be easily extended with custom field types). - **name** is a property of data item associated with the column. - **title** is a text to be displayed in the header of the column. If `title` is not specified, the `name` will be used instead. - **align** is alignment of text in the cell. Accepts following values `"left"|"center"|"right"`. - **width** is a width of the column. - **visible** is a boolean specifying whether to show a column or not. (version added: 1.3) - **css** is a string representing css classes to be attached to the table cell. - **headercss** is a string representing css classes to be attached to the table header cell. If not specified, then **css** is attached instead. - **filtercss** is a string representing css classes to be attached to the table filter row cell. If not specified, then **css** is attached instead. - **insertcss** is a string representing css classes to be attached to the table insert row cell. If not specified, then **css** is attached instead. - **editcss** is a string representing css classes to be attached to the table edit row cell. If not specified, then **css** is attached instead. - **filtering** is a boolean specifying whether or not column has filtering (`filterTemplate()` is rendered and `filterValue()` is included in load filter object). - **inserting** is a boolean specifying whether or not column has inserting (`insertTemplate()` is rendered and `insertValue()` is included in inserting item). - **editing** is a boolean specifying whether or not column has editing (`editTemplate()` is rendered and `editValue()` is included in editing item). - **sorting** is a boolean specifying whether or not column has sorting ability. - **sorter** is a string or a function specifying how to sort item by the field. The string is a key of sorting strategy in the registry `jsGrid.sortStrategies` (the registry can be easily extended with custom sorting functions). Sorting function has the signature `function(value1, value2) { return -1|0|1; }`. - **headerTemplate** is a function to create column header content. It should return markup as string, DomNode or jQueryElement. - **itemTemplate** is a function to create cell content. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterTemplate** is a function to create filter row cell content. It should return markup as string, DomNode or jQueryElement. - **insertTemplate** is a function to create insert row cell content. It should return markup as string, DomNode or jQueryElement. - **editTemplate** is a function to create cell content of editing row. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterValue** is a function returning the value of filter property associated with the column. - **insertValue** is a function returning the value of inserting item property associated with the column. - **editValue** is a function returning the value of editing item property associated with the column. - **cellRenderer** is a function to customize cell rendering. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. The function should return markup as a string, jQueryElement or DomNode representing table cell `td`. - **validate** is a string as validate rule name or validation function or a validation configuration object or an array of validation configuration objects. Read more details about validation in the [Validation section](#validation). Specific field options depends on concrete field type. Read about build-in fields in [Grid Fields](#grid-fields) section. ### data An array of items to be displayed in the grid. The option should be used to provide static data. Use the `controller` option to provide non static data. ### autoload (default `false`) A boolean value specifying whether `controller.loadData` will be called when grid is rendered. ### controller An object or function returning an object with the following structure: ```javascript { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop } ``` - **loadData** is a function returning an array of data or jQuery promise that will be resolved with an array of data (when `pageLoading` is `true` instead of object the structure `{ data: [items], itemsCount: [total items count] }` should be returned). Accepts filter parameter including current filter options and paging parameters when `pageLoading` is `true`. - **insertItem** is a function returning inserted item or jQuery promise that will be resolved with inserted item. Accepts inserting item object. - **updateItem** is a function returning updated item or jQuery promise that will be resolved with updated item. Accepts updating item object. - **deleteItem** is a function deleting item. Returns jQuery promise that will be resolved when deletion is completed. Accepts deleting item object. Read more about controller interface in [Grid Controller](#grid-controller) section. ### width (default: `"auto"`) Specifies the overall width of the grid. Accepts all value types accepting by `jQuery.width`. ### height (default: `"auto"`) Specifies the overall height of the grid including the pager. Accepts all value types accepting by `jQuery.height`. ### heading (default: `true`) A boolean value specifies whether to show grid header or not. ### filtering (default: `false`) A boolean value specifies whether to show filter row or not. ### inserting (default: `false`) A boolean value specifies whether to show inserting row or not. ### editing (default: `false`) A boolean value specifies whether editing is allowed. ### selecting (default: `true`) A boolean value specifies whether to highlight grid rows on hover. ### sorting (default: `false`) A boolean value specifies whether sorting is allowed. ### paging (default: `false`) A boolean value specifies whether data is displayed by pages. ### pageLoading (default: `false`) A boolean value specifies whether to load data by page. When `pageLoading` is `true` the `loadData` method of controller accepts `filter` parameter with two additional properties `pageSize` and `pageIndex`. ### insertRowLocation (default: `"bottom"`) Specifies the location of an inserted row within the grid. When `insertRowLocation` is `"bottom"` the new row will appear at the bottom of the grid. When set to `"top"`, the new row will appear at the top. ### rowClass A string or a function specifying row css classes. A string contains classes separated with spaces. A function has signature `function(item, itemIndex)`. It accepts the data item and index of the item. It should returns a string containing classes separated with spaces. ### rowClick A function handling row click. Accepts single argument with following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` By default `rowClick` performs row editing when `editing` is `true`. ### rowDoubleClick A function handling row double click. Accepts single argument with the following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` ### noDataContent (default `"Not found"`) A string or a function returning a markup, jQueryElement or DomNode specifying the content to be displayed when `data` is an empty array. ### confirmDeleting (default `true`) A boolean value specifying whether to ask user to confirm item deletion. ### deleteConfirm (default `"Are you sure?"`) A string or a function returning string specifying delete confirmation message to be displayed to the user. A function has the signature `function(item)` and accepts item to be deleted. ### pagerContainer (default `null`) A jQueryElement or DomNode to specify where to render a pager. Used for external pager rendering. When it is equal to `null`, the pager is rendered at the bottom of the grid. ### pageIndex (default `1`) An integer value specifying current page index. Applied only when `paging` is `true`. ### pageSize (default `20`) An integer value specifying the amount of items on the page. Applied only when `paging` is `true`. ### pageButtonCount (default `15`) An integer value specifying the maximum amount of page buttons to be displayed in the pager. ### pagerFormat A string specifying pager format. The default value is `"Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}"` There are placeholders that can be used in the format: ```javascript {first} // link to first page {prev} // link to previous page {pages} // page links {next} // link to next page {last} // link to last page {pageIndex} // current page index {pageCount} // total amount of pages {itemCount} // total amount of items ``` ### pageNextText (default `"Next"`) A string specifying the text of the link to the next page. ### pagePrevText (default `"Prev"`) A string specifying the text of the link to the previous page. ### pageFirstText (default `"First"`) A string specifying the text of the link to the first page. ### pageLastText (default `"Last"`) A string specifying the text of the link to the last page. ### pageNavigatorNextText (default `"..."`) A string specifying the text of the link to move to next set of page links, when total amount of pages more than `pageButtonCount`. ### pageNavigatorPrevText (default `"..."`) A string specifying the text of the link to move to previous set of page links, when total amount of pages more than `pageButtonCount`. ### invalidMessage (default `"Invalid data entered!"`) A string specifying the text of the alert message, when invalid data was entered. ### invalidNotify A function triggered, when invalid data was entered. By default all violated validators messages are alerted. The behavior can be customized by providing custom function. The function accepts a single argument with the following structure: ```javascript { item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` In the following example error messages are printed in the console instead of alerting: ```javascript $("#grid").jsGrid({ ... invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.field + ": " + error.message; }); console.log(messages); } ... }); ``` ### loadIndication (default `true`) A boolean value specifying whether to show loading indication during controller operations execution. ### loadIndicationDelay (default `500`) An integer value specifying the delay in ms before showing load indication. Applied only when `loadIndication` is `true`. ### loadMessage (default `"Please, wait..."`) A string specifying the text of loading indication panel. Applied only when `loadIndication` is `true`. ### loadShading (default `true`) A boolean value specifying whether to show overlay (shader) over grid content during loading indication. Applied only when `loadIndication` is `true`. ### loadIndicator An object or a function returning an object representing grid load indicator. Load indicator could be any js object supporting two methods `show` and `hide`. `show` is called on each loading start. `hide` method is called on each loading finish. Read more about custom load indicator in the [Load Indication](#load-indication) section. ### loadStrategy An object or a function returning an object representing grid load strategy. Load strategy defines behavior of the grid after loading data (any interaction with grid controller methods including data manipulation like inserting, updating and removing). There are two build-in load strategies: `DirectLoadingStrategy` and `PageLoadingStrategy`. Load strategy depends on `pageLoading` option value. For advanced scenarios custom load strategy can be provided. Read more about custom load strategies in the [Load Strategies](#load-strategies) section. ### updateOnResize (default `true`) A boolean value specifying whether to refresh grid on window resize event. ### rowRenderer (default `null`) A function to customize row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### headerRowRenderer (default `null`) A function to customize grid header row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### filterRowRenderer (default `null`) A function to customize grid filter row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### insertRowRenderer (default `null`) A function to customize grid inserting row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### editRowRenderer (default `null`) A function to customize editing row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### pagerRenderer (default `null`) > version added: 1.2 A function to customize pager rendering. The function accepts a single argument with the following structure: ```javascript { pageIndex, // index of the currently opened page pageCount // total amount of grid pages } ``` The function should return markup as a string, jQueryElement or DomNode representing the pager. If `pagerRenderer` is specified, then `pagerFormat` option will be ignored. ## Grid Fields All fields supporting by grid are stored in `jsGrid.fields` object, where key is a type of the field and the value is the field class. `jsGrid.fields` contains following build-in fields: ```javascript { text: { ... }, // simple text input number: { ... }, // number input select: { ... }, // select control checkbox: { ... }, // checkbox input textarea: { ... }, // textarea control (renders textarea for inserting and editing and text input for filtering) control: { ... } // control field with delete and editing buttons for data rows, search and add buttons for filter and inserting row } ``` Each build-in field can be easily customized with general configuration properties described in [fields](#fields) section and custom field-specific properties described below. ### text Text field renders `<input type="text">` in filter, inserting and editing rows. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### number Number field renders `<input type="number">` in filter, inserting and editing rows. Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "right", // right text alignment readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### select Select field renders `<select>` control in filter, inserting and editing rows. Custom properties: ```javascript { align: "center", // center text alignment autosearch: true, // triggers searching when the user changes the selected item in the filter items: [], // an array of items for select valueField: "", // name of property of item to be used as value textField: "", // name of property of item to be used as displaying value selectedIndex: -1, // index of selected item by default valueType: "number|string", // the data type of the value readOnly: false // a boolean defines whether select is readonly (added in v1.4) } ``` If valueField is not defined, then the item index is used instead. If textField is not defined, then item itself is used to display value. For instance the simple select field config may look like: ```javascript { name: "Country", type: "select", items: [ "", "United States", "Canada", "United Kingdom" ] } ``` or more complex with items as objects: ```javascript { name: "Country", type: "select" items: [ { Name: "", Id: 0 }, { Name: "United States", Id: 1 }, { Name: "Canada", Id: 2 }, { Name: "United Kingdom", Id: 3 } ], valueField: "Id", textField: "Name" } ``` `valueType` defines whether the field value should be converted to a number or returned as a string. The value of the option is determined automatically depending on the data type of `valueField` of the first item, but it can be overridden. ### checkbox Checkbox field renders `<input type="checkbox">` in filter, inserting and editing rows. Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked). Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "center", // center text alignment autosearch: true // triggers searching when the user clicks checkbox in filter } ``` ### textarea Textarea field renders `<textarea>` in inserting and editing rows and `<input type="text">` in filter row. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether textarea is readonly (added in v1.4) } ``` ### control Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. It also renders button switching between filtering and searching in header row. Custom properties: ```javascript { editButton: true, // show edit button deleteButton: true, // show delete button clearFilterButton: true, // show clear filter button modeSwitchButton: true, // show switching filtering/inserting button align: "center", // center content alignment width: 50, // default column width is 50px filtering: false, // disable filtering for column inserting: false, // disable inserting for column editing: false, // disable editing for column sorting: false, // disable sorting for column searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode editButtonTooltip: "Edit", // tooltip of edit item button deleteButtonTooltip: "Delete", // tooltip of delete item button searchButtonTooltip: "Search", // tooltip of search button clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button insertButtonTooltip: "Insert", // tooltip of insert button updateButtonTooltip: "Update", // tooltip of update item button cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button } ``` ### Custom Field If you need a completely custom field, the object `jsGrid.fields` can be easily extended. In this example we define new grid field `date`: ```javascript var MyDateField = function(config) { jsGrid.Field.call(this, config); }; MyDateField.prototype = new jsGrid.Field({ css: "date-field", // redefine general property 'css' align: "center", // redefine general property 'align' myCustomProperty: "foo", // custom property sorter: function(date1, date2) { return new Date(date1) - new Date(date2); }, itemTemplate: function(value) { return new Date(value).toDateString(); }, insertTemplate: function(value) { return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() }); }, editTemplate: function(value) { return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value)); }, insertValue: function() { return this._insertPicker.datepicker("getDate").toISOString(); }, editValue: function() { return this._editPicker.datepicker("getDate").toISOString(); } }); jsGrid.fields.date = MyDateField; ``` To have all general grid field properties custom field class should inherit `jsGrid.Field` class or any other field class. Here `itemTemplate` just returns the string representation of a date. `insertTemplate` and `editTemplate` create jQuery UI datePicker for inserting and editing row. Of course jquery ui library should be included to make it work. `insertValue` and `editValue` return date to insert and update items accordingly. We also defined date specific sorter. Now, our new field `date` can be used in the grid config as follows: ```javascript { fields: [ ... { type: "date", myCustomProperty: "bar" }, ... ] } ``` ## Methods jsGrid methods could be called with `jsGrid` jQuery plugin or directly. To use jsGrid plugin to call a method, just call `jsGrid` with method name and required parameters as next arguments: ```javascript // calling method with jQuery plugin $("#grid").jsGrid("methodName", param1, param2); ``` To call method directly you need to retrieve grid instance or just create grid with the constructor: ```javascript // retrieve grid instance from element data var grid = $("#grid").data("JSGrid"); // create grid with the constructor var grid = new jsGrid.Grid($("#grid"), { ... }); // call method directly grid.methodName(param1, param2); ``` ### cancelEdit() Cancels row editing. ```javascript $("#grid").jsGrid("cancelEdit"); ``` ### clearFilter(): `Promise` Clears current filter and performs search with empty filter. Returns jQuery promise resolved when data filtering is completed. ```javascript $("#grid").jsGrid("clearFilter").done(function() { console.log("filtering completed"); }); ``` ### clearInsert() Clears current inserting row. ```javascript $("#grid").jsGrid("clearInsert"); ``` ### deleteItem(item|$row|rowNode): `Promise` Removes specified row from the grid. Returns jQuery promise resolved when deletion is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // delete row by item reference $("#grid").jsGrid("deleteItem", item); // delete row by jQueryElement $("#grid").jsGrid("deleteItem", $(".specific-row")); // delete row by DomNode $("#grid").jsGrid("deleteItem", rowNode); ``` ### destroy() Destroys the grid and brings the Node to its original state. ```javascript $("#grid").jsGrid("destroy"); ``` ### editItem(item|$row|rowNode) Sets grid editing row. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // edit row by item reference $("#grid").jsGrid("editItem", item); // edit row by jQueryElement $("#grid").jsGrid("editItem", $(".specific-row")); // edit row by DomNode $("#grid").jsGrid("editItem", rowNode); ``` ### getFilter(): `Object` Get grid filter as a plain object. ```javascript var filter = $("#grid").jsGrid("getFilter"); ``` ### getSorting(): `Object` > version added: 1.2 Get grid current sorting params as a plain object with the following format: ```javascript { field, // the name of the field by which grid is sorted order // 'asc' or 'desc' depending on sort order } ``` ```javascript var sorting = $("#grid").jsGrid("getSorting"); ``` ### fieldOption(fieldName|fieldIndex, optionName, [optionValue]) > version added: 1.3 Gets or sets the value of a field option. **fieldName|fieldIndex** is the name or the index of the field to get/set the option value (if the grid contains more than one field with the same name, the first field will be used). **optionName** is the name of the field option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the field option `optionName` will be returned. ```javascript // hide the field "ClientName" $("#grid").jsGrid("fieldOption", "ClientName", "visible", false); // get width of the 2nd field var secondFieldOption = $("#grid").jsGrid("fieldOption", 1, "width"); ``` ### insertItem([item]): `Promise` Inserts row into the grid based on item. Returns jQuery promise resolved when insertion is completed. **item** is the item to pass to `controller.insertItem`. If `item` is not specified the data from inserting row will be inserted. ```javascript // insert item from inserting row $("#grid").jsGrid("insertItem"); // insert item $("#grid").jsGrid("insertItem", { Name: "John", Age: 25, Country: 2 }).done(function() { console.log("insertion completed"); }); ``` ### loadData([filter]): `Promise` Loads data calling corresponding `controller.loadData` method. Returns jQuery promise resolved when data loading is completed. It preserves current sorting and paging unlike the `search` method . **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // load data with current grid filter $("#grid").jsGrid("loadData"); // loadData with custom filter $("#grid").jsGrid("loadData", { Name: "John" }).done(function() { console.log("data loaded"); }); ``` ### exportData([options]) Transforms the grid data into the specified output type. Output can be formatted, filtered or modified by providing options. Currently only supports CSV output. ```javascript //Basic export var csv = $("#grid").jsGrid("exportData"); //Full Options var csv = $("#grid").jsGrid("exportData", { type: "csv", //Only CSV supported subset: "all" | "visible", //Visible will only output the currently displayed page delimiter: "|", //If using csv, the character to seperate fields includeHeaders: true, //Include header row in output encapsulate: true, //Surround each field with qoutation marks; needed for some systems newline: "\r\n", //Newline character to use //Takes each item and returns true if it should be included in output. //Executed only on the records within the given subset above. filter: function(item){return true}, //Transformations are a way to modify the display value of the output. //Provide a key of the field name, and a function that takes the current value. transformations: { "Married": function(value){ if (value === true) return "Yes" if (value !== false) return "No" } } }); ``` ### openPage(pageIndex) Opens the page of specified index. **pageIndex** is one-based index of the page to open. The value should be in range from 1 to [total amount of pages]. ### option(optionName, [optionValue]) Gets or sets the value of an option. **optionName** is the name of the option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the option `optionName` will be returned. ```javascript // turn off paging $("#grid").jsGrid("option", "paging", false); // get current page index var pageIndex = $("#grid").jsGrid("option", "pageIndex"); ``` ### refresh() Refreshes the grid. Renders the grid body and pager content, recalculates sizes. ```javascript $("#grid").jsGrid("refresh"); ``` ### render(): `Promise` Performs complete grid rendering. If option `autoload` is `true` calls `controller.loadData`. The state of the grid like current page and sorting is retained. Returns jQuery promise resolved when data loading is completed. If auto-loading is disabled the promise is instantly resolved. ```javascript $("#grid").jsGrid("render").done(function() { console.log("rendering completed and data loaded"); }); ``` ### reset() Resets the state of the grid. Goes to the first data page, resets sorting, and then calls `refresh`. ```javascript $("#grid").jsGrid("reset"); ``` ### rowByItem(item): `jQueryElement` > version added: 1.3 Gets the row jQuery element corresponding to the item. **item** is the item corresponding to the row. ```javascript var $row = $("#grid").jsGrid("rowByItem", item); ``` ### search([filter]): `Promise` Performs filtering of the grid. Returns jQuery promise resolved when data loading is completed. It resets current sorting and paging unlike the `loadData` method. **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // search with current grid filter $("#grid").jsGrid("search"); // search with custom filter $("#grid").jsGrid("search", { Name: "John" }).done(function() { console.log("filtering completed"); }); ``` ### showPrevPages() Shows previous set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showPrevPages"); ``` ### showNextPages() Shows next set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showNextPages"); ``` ### sort(sortConfig|field, [order]): `Promise` Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed. **sortConfig** is the plain object of the following structure `{ field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }` **field** is the field to sort by. It could be zero-based field index or field name or field reference **order** is the sorting order. Accepts the following values: "asc"|"desc" If `order` is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or `"asc"` for sorting by another field. When grid data is loaded by pages (`pageLoading` is `true`) sorting calls `controller.loadData` with sorting parameters. Read more in [Grid Controller](#grid-controller) section. ```javascript // sorting grid by first field $("#grid").jsGrid("sort", 0); // sorting grid by field "Name" in descending order $("#grid").jsGrid("sort", { field: "Name", order: "desc" }); // sorting grid by myField in ascending order $("#grid").jsGrid("sort", myField, "asc").done(function() { console.log("sorting completed"); }); ``` ### updateItem([item|$row|rowNode], [editedItem]): `Promise` Updates item and row of the grid. Returns jQuery promise resolved when update is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. **editedItem** is the changed item to pass to `controller.updateItem`. If `item|$row|rowNode` is not specified then editing row will be updated. If `editedItem` is not specified the data from editing row will be taken. ```javascript // update currently editing row $("#grid").jsGrid("updateItem"); // update currently editing row with specified data $("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 }); // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference) $("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() { console.log("update completed"); }); ``` ### jsGrid.locale(localeName|localeConfig) > version added: 1.4 Set current locale of all grids. **localeName|localeConfig** is the name of the supported locale (see [available locales](src/i18n)) or a custom localization config. Find more information on custom localization config in [Localization](#localization). ```javascript // set French locale jsGrid.locale("fr"); ``` ### jsGrid.setDefaults(config) Set default options for all grids. ```javascript jsGrid.setDefaults({ filtering: true, inserting: true }); ``` ### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript jsGrid.setDefaults("text", { width: 150, css: "text-field-cls" }); ``` ## Callbacks jsGrid allows to specify a callback function to be executed on a particular event. The following callbacks are supported: ```javascript { onDataLoading: function(args) {}, // before controller.loadData onDataLoaded: function(args) {}, // on done of controller.loadData onDataExporting: function() {}, // before data export onInit: function(args) {}, // after grid initialization onItemInserting: function(args) {}, // before controller.insertItem onItemInserted: function(args) {}, // on done of controller.insertItem onItemUpdating: function(args) {}, // before controller.updateItem onItemUpdated: function(args) {}, // on done of controller.updateItem onItemDeleting: function(args) {}, // before controller.deleteItem onItemDeleted: function(args) {}, // on done of controller.deleteItem onItemInvalid: function(args) {}, // after item validation, in case data is invalid onError: function(args) {}, // on fail of any controller call onOptionChanging: function(args) {}, // before changing the grid option onOptionChanged: function(args) {}, // after changing the grid option onPageChanged: function(args) {}, // after changing the current page onRefreshing: function(args) {}, // before grid refresh onRefreshed: function(args) {}, // after grid refresh } ``` ### onDataLoading Fires before data loading. Has the following arguments: ```javascript { grid // grid instance filter // loading filter object } ``` #### Cancel Data Loading > version added: 1.2 To cancel data loading set `args.cancel = true`. In the following example loading is canceled when the filter has empty 'name' field: ```javascript $("#grid").jsGrid({ ... onDataLoading: function(args) { // cancel loading data if 'name' is empty if(args.filter.name === "") { args.cancel = true; } } }); ``` ### onDataLoaded Fires after data loading. Has the following arguments: ```javascript { grid // grid instance data // load result (array of items or data structure for loading by page scenario) } ``` In the following example the loaded data is written to the browser console. ```javascript $("#grid").jsGrid({ ... onDataLoaded: function(args) { console.log(args.data); } }); ``` ### onInit > version added: 1.5 Fires after grid initialization right before rendering. Usually used to get grid instance. Has the following arguments: ```javascript { grid // grid instance } ``` In the following example we get the grid instance on initialization: ```javascript var gridInstance; $("#grid").jsGrid({ ... onInit: function(args) { gridInstance = args.grid; } }); ``` ### onError Fires when controller handler promise failed. Has the following arguments: ```javascript { grid // grid instance args // an array of arguments provided to fail promise handler } ``` ### onItemDeleting Fires before item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index } ``` #### Cancel Item Deletion > version added: 1.2 To cancel item deletion set `args.cancel = true`. This allows to do a validation before performing the actual deletion. In the following example the deletion of items marked as `protected` is canceled: ```javascript $("#grid").jsGrid({ ... onItemDeleting: function(args) { // cancel deletion of the item with 'protected' field if(args.item.protected) { args.cancel = true; } } }); ``` ### onItemDeleted Fires after item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index } ``` ### onItemEditing > version added: 1.4 Fires before item editing. Has the following arguments: ```javascript { grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index } ``` #### Cancel Item Editing To cancel item editing set `args.cancel = true`. This allows to prevent row from editing conditionally. In the following example the editing of the row for item with 'ID' = 0 is canceled: ```javascript $("#grid").jsGrid({ ... onItemEditing: function(args) { // cancel editing of the row of item with field 'ID' = 0 if(args.item.ID === 0) { args.cancel = true; } } }); ``` ### onItemInserting Fires before item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserting item } ``` #### Cancel Item Insertion > version added: 1.2 To cancel item insertion set `args.cancel = true`. This allows to do a validation before performing the actual insertion. In the following example insertion of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemInserting: function(args) { // cancel insertion of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemInserted Fires after item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserted item } ``` ### onItemInvalid Fired when item is not following validation rules on inserting or updating. Has the following arguments: ```javascript { grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` The following handler prints errors on the console ```javascript $("#grid").jsGrid({ ... onItemInvalid: function(args) { // prints [{ field: "Name", message: "Enter client name" }] console.log(args.errors); } }); ``` ### onItemUpdating Fires before item update. Has the following arguments: ```javascript { grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing } ``` #### Cancel Item Update > version added: 1.2 To cancel item update set `args.cancel = true`. This allows to do a validation before performing the actual update. In the following example update of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemUpdating: function(args) { // cancel update of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemUpdated Fires after item update. Has the following arguments: ```javascript { grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing } ``` ### onOptionChanging Fires before grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option } ``` ### onOptionChanged Fires after grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: [ "required", { validator: "range", param: [21, 80] }, function(value, item) { return item.IsRetired ? value > 55 : true; } ] }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The option `loadStrategy` allows to specify a custom load strategy to customize the behavior of the grid. The easiest way to do it is to inherit from existing strategy. By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item. ```javascript var MyCustomDirectLoadStrategy = function(grid) { jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid); }; MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy(); MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.refresh(); }; // use custom strategy in grid config $("#grid").jsGrid({ loadStrategy: function() { return new MyCustomDirectLoadStrategy(this); }, ... }); ``` ## Load Indication By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the `loadIndicator` option. Set an object or a function returning an object supporting the following interface: ```javascript { show: function() { ... } // called on loading start hide: | 4 | README: Fixed example which contained invalid logic | 2 | .md | md | mit | tabalinas/jsgrid |
10067853 | <NME> README.md <BEF> # jsGrid Lightweight Grid jQuery Plugin [](https://travis-ci.org/tabalinas/jsgrid) Project site [js-grid.com](http://js-grid.com/) **jsGrid** is a lightweight client-side data grid control based on jQuery. It supports basic grid operations like inserting, filtering, editing, deleting, paging, sorting, and validating. jsGrid is tunable and allows to customize appearance and components.  ## Table of contents * [Demos](#demos) * [Installation](#installation) * [Basic Usage](#basic-usage) * [Configuration](#configuration) * [Grid Fields](#grid-fields) * [Methods](#methods) * [Callbacks](#callbacks) * [Grid Controller](#grid-controller) * [Validation](#validation) * [Localization](#localization) * [Sorting Strategies](#sorting-strategies) * [Load Strategies](#load-strategies) * [Load Indication](#load-indication) * [Requirement](#requirement) * [Compatibility](#compatibility) ## Demos See [Demos](http://js-grid.com/demos/) on project site. Sample projects showing how to use jsGrid with the most popular backend technologies * **PHP** - https://github.com/tabalinas/jsgrid-php * **ASP.NET WebAPI** - https://github.com/tabalinas/jsgrid-webapi * **Express (NodeJS)** - https://github.com/tabalinas/jsgrid-express * **Ruby on Rail** - https://github.com/tabalinas/jsgrid-rails * **Django (Python)** - https://github.com/tabalinas/jsgrid-django ## Installation Install jsgrid with bower: ```bash $ bower install js-grid --save ``` Find jsGrid cdn links [here](https://cdnjs.com/libraries/jsgrid). ## Basic Usage Ensure that jQuery library of version 1.8.3 or later is included. Include `jsgrid.min.js`, `jsgrid-theme.min.css`, and `jsgrid.min.css` files into the web page. Create grid applying jQuery plugin `jsGrid` with grid config as follows: ```javascript $("#jsGrid").jsGrid({ width: "100%", height: "400px", filtering: true, editing: true, sorting: true, paging: true, data: db.clients, fields: [ { name: "Name", type: "text", width: 150 }, { name: "Age", type: "number", width: 50 }, { name: "Address", type: "text", width: 200 }, { name: "Country", type: "select", items: db.countries, valueField: "Id", textField: "Name" }, { name: "Married", type: "checkbox", title: "Is Married", sorting: false }, { type: "control" } ] }); ``` ## Configuration The config object may contain following options (default values are specified below): ```javascript { fields: [], data: [], autoload: false, controller: { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop }, width: "auto", height: "auto", heading: true, filtering: false, inserting: false, editing: false, selecting: true, sorting: false, paging: false, pageLoading: false, insertRowLocation: "bottom", rowClass: function(item, itemIndex) { ... }, rowClick: function(args) { ... }, rowDoubleClick: function(args) { ... }, noDataContent: "Not found", confirmDeleting: true, deleteConfirm: "Are you sure?", pagerContainer: null, pageIndex: 1, pageSize: 20, pageButtonCount: 15, pagerFormat: "Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}", pagePrevText: "Prev", pageNextText: "Next", pageFirstText: "First", pageLastText: "Last", pageNavigatorNextText: "...", pageNavigatorPrevText: "...", invalidNotify: function(args) { ... } invalidMessage: "Invalid data entered!", loadIndication: true, loadIndicationDelay: 500, loadMessage: "Please, wait...", loadShading: true, loadIndicator: function(config) { ... } loadStrategy: function(config) { ... } updateOnResize: true, rowRenderer: null, headerRowRenderer: null, filterRowRenderer: null, insertRowRenderer: null, editRowRenderer: null, pagerRenderer: null } ``` ### fields An array of fields (columns) of the grid. Each field has general options and specific options depending on field type. General options peculiar to all field types: ```javascript { type: "", name: "", title: "", align: "", width: 100, visible: true, css: "", headercss: "", filtercss: "", insertcss: "", editcss: "", filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", headerTemplate: function() { ... }, itemTemplate: function(value, item) { ... }, filterTemplate: function() { ... }, insertTemplate: function() { ... }, editTemplate: function(value, item) { ... }, filterValue: function() { ... }, insertValue: function() { ... }, editValue: function() { ... }, cellRenderer: null, validate: null } ``` - **type** is a string key of field (`"text"|"number"|"checkbox"|"select"|"textarea"|"control"`) in fields registry `jsGrid.fields` (the registry can be easily extended with custom field types). - **name** is a property of data item associated with the column. - **title** is a text to be displayed in the header of the column. If `title` is not specified, the `name` will be used instead. - **align** is alignment of text in the cell. Accepts following values `"left"|"center"|"right"`. - **width** is a width of the column. - **visible** is a boolean specifying whether to show a column or not. (version added: 1.3) - **css** is a string representing css classes to be attached to the table cell. - **headercss** is a string representing css classes to be attached to the table header cell. If not specified, then **css** is attached instead. - **filtercss** is a string representing css classes to be attached to the table filter row cell. If not specified, then **css** is attached instead. - **insertcss** is a string representing css classes to be attached to the table insert row cell. If not specified, then **css** is attached instead. - **editcss** is a string representing css classes to be attached to the table edit row cell. If not specified, then **css** is attached instead. - **filtering** is a boolean specifying whether or not column has filtering (`filterTemplate()` is rendered and `filterValue()` is included in load filter object). - **inserting** is a boolean specifying whether or not column has inserting (`insertTemplate()` is rendered and `insertValue()` is included in inserting item). - **editing** is a boolean specifying whether or not column has editing (`editTemplate()` is rendered and `editValue()` is included in editing item). - **sorting** is a boolean specifying whether or not column has sorting ability. - **sorter** is a string or a function specifying how to sort item by the field. The string is a key of sorting strategy in the registry `jsGrid.sortStrategies` (the registry can be easily extended with custom sorting functions). Sorting function has the signature `function(value1, value2) { return -1|0|1; }`. - **headerTemplate** is a function to create column header content. It should return markup as string, DomNode or jQueryElement. - **itemTemplate** is a function to create cell content. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterTemplate** is a function to create filter row cell content. It should return markup as string, DomNode or jQueryElement. - **insertTemplate** is a function to create insert row cell content. It should return markup as string, DomNode or jQueryElement. - **editTemplate** is a function to create cell content of editing row. It should return markup as string, DomNode or jQueryElement. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. - **filterValue** is a function returning the value of filter property associated with the column. - **insertValue** is a function returning the value of inserting item property associated with the column. - **editValue** is a function returning the value of editing item property associated with the column. - **cellRenderer** is a function to customize cell rendering. The function signature is `function(value, item)`, where `value` is a value of column property of data item, and `item` is a row data item. The function should return markup as a string, jQueryElement or DomNode representing table cell `td`. - **validate** is a string as validate rule name or validation function or a validation configuration object or an array of validation configuration objects. Read more details about validation in the [Validation section](#validation). Specific field options depends on concrete field type. Read about build-in fields in [Grid Fields](#grid-fields) section. ### data An array of items to be displayed in the grid. The option should be used to provide static data. Use the `controller` option to provide non static data. ### autoload (default `false`) A boolean value specifying whether `controller.loadData` will be called when grid is rendered. ### controller An object or function returning an object with the following structure: ```javascript { loadData: $.noop, insertItem: $.noop, updateItem: $.noop, deleteItem: $.noop } ``` - **loadData** is a function returning an array of data or jQuery promise that will be resolved with an array of data (when `pageLoading` is `true` instead of object the structure `{ data: [items], itemsCount: [total items count] }` should be returned). Accepts filter parameter including current filter options and paging parameters when `pageLoading` is `true`. - **insertItem** is a function returning inserted item or jQuery promise that will be resolved with inserted item. Accepts inserting item object. - **updateItem** is a function returning updated item or jQuery promise that will be resolved with updated item. Accepts updating item object. - **deleteItem** is a function deleting item. Returns jQuery promise that will be resolved when deletion is completed. Accepts deleting item object. Read more about controller interface in [Grid Controller](#grid-controller) section. ### width (default: `"auto"`) Specifies the overall width of the grid. Accepts all value types accepting by `jQuery.width`. ### height (default: `"auto"`) Specifies the overall height of the grid including the pager. Accepts all value types accepting by `jQuery.height`. ### heading (default: `true`) A boolean value specifies whether to show grid header or not. ### filtering (default: `false`) A boolean value specifies whether to show filter row or not. ### inserting (default: `false`) A boolean value specifies whether to show inserting row or not. ### editing (default: `false`) A boolean value specifies whether editing is allowed. ### selecting (default: `true`) A boolean value specifies whether to highlight grid rows on hover. ### sorting (default: `false`) A boolean value specifies whether sorting is allowed. ### paging (default: `false`) A boolean value specifies whether data is displayed by pages. ### pageLoading (default: `false`) A boolean value specifies whether to load data by page. When `pageLoading` is `true` the `loadData` method of controller accepts `filter` parameter with two additional properties `pageSize` and `pageIndex`. ### insertRowLocation (default: `"bottom"`) Specifies the location of an inserted row within the grid. When `insertRowLocation` is `"bottom"` the new row will appear at the bottom of the grid. When set to `"top"`, the new row will appear at the top. ### rowClass A string or a function specifying row css classes. A string contains classes separated with spaces. A function has signature `function(item, itemIndex)`. It accepts the data item and index of the item. It should returns a string containing classes separated with spaces. ### rowClick A function handling row click. Accepts single argument with following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` By default `rowClick` performs row editing when `editing` is `true`. ### rowDoubleClick A function handling row double click. Accepts single argument with the following structure: ```javascript { item // data item itemIndex // data item index event // jQuery event } ``` ### noDataContent (default `"Not found"`) A string or a function returning a markup, jQueryElement or DomNode specifying the content to be displayed when `data` is an empty array. ### confirmDeleting (default `true`) A boolean value specifying whether to ask user to confirm item deletion. ### deleteConfirm (default `"Are you sure?"`) A string or a function returning string specifying delete confirmation message to be displayed to the user. A function has the signature `function(item)` and accepts item to be deleted. ### pagerContainer (default `null`) A jQueryElement or DomNode to specify where to render a pager. Used for external pager rendering. When it is equal to `null`, the pager is rendered at the bottom of the grid. ### pageIndex (default `1`) An integer value specifying current page index. Applied only when `paging` is `true`. ### pageSize (default `20`) An integer value specifying the amount of items on the page. Applied only when `paging` is `true`. ### pageButtonCount (default `15`) An integer value specifying the maximum amount of page buttons to be displayed in the pager. ### pagerFormat A string specifying pager format. The default value is `"Pages: {first} {prev} {pages} {next} {last} {pageIndex} of {pageCount}"` There are placeholders that can be used in the format: ```javascript {first} // link to first page {prev} // link to previous page {pages} // page links {next} // link to next page {last} // link to last page {pageIndex} // current page index {pageCount} // total amount of pages {itemCount} // total amount of items ``` ### pageNextText (default `"Next"`) A string specifying the text of the link to the next page. ### pagePrevText (default `"Prev"`) A string specifying the text of the link to the previous page. ### pageFirstText (default `"First"`) A string specifying the text of the link to the first page. ### pageLastText (default `"Last"`) A string specifying the text of the link to the last page. ### pageNavigatorNextText (default `"..."`) A string specifying the text of the link to move to next set of page links, when total amount of pages more than `pageButtonCount`. ### pageNavigatorPrevText (default `"..."`) A string specifying the text of the link to move to previous set of page links, when total amount of pages more than `pageButtonCount`. ### invalidMessage (default `"Invalid data entered!"`) A string specifying the text of the alert message, when invalid data was entered. ### invalidNotify A function triggered, when invalid data was entered. By default all violated validators messages are alerted. The behavior can be customized by providing custom function. The function accepts a single argument with the following structure: ```javascript { item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` In the following example error messages are printed in the console instead of alerting: ```javascript $("#grid").jsGrid({ ... invalidNotify: function(args) { var messages = $.map(args.errors, function(error) { return error.field + ": " + error.message; }); console.log(messages); } ... }); ``` ### loadIndication (default `true`) A boolean value specifying whether to show loading indication during controller operations execution. ### loadIndicationDelay (default `500`) An integer value specifying the delay in ms before showing load indication. Applied only when `loadIndication` is `true`. ### loadMessage (default `"Please, wait..."`) A string specifying the text of loading indication panel. Applied only when `loadIndication` is `true`. ### loadShading (default `true`) A boolean value specifying whether to show overlay (shader) over grid content during loading indication. Applied only when `loadIndication` is `true`. ### loadIndicator An object or a function returning an object representing grid load indicator. Load indicator could be any js object supporting two methods `show` and `hide`. `show` is called on each loading start. `hide` method is called on each loading finish. Read more about custom load indicator in the [Load Indication](#load-indication) section. ### loadStrategy An object or a function returning an object representing grid load strategy. Load strategy defines behavior of the grid after loading data (any interaction with grid controller methods including data manipulation like inserting, updating and removing). There are two build-in load strategies: `DirectLoadingStrategy` and `PageLoadingStrategy`. Load strategy depends on `pageLoading` option value. For advanced scenarios custom load strategy can be provided. Read more about custom load strategies in the [Load Strategies](#load-strategies) section. ### updateOnResize (default `true`) A boolean value specifying whether to refresh grid on window resize event. ### rowRenderer (default `null`) A function to customize row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### headerRowRenderer (default `null`) A function to customize grid header row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### filterRowRenderer (default `null`) A function to customize grid filter row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### insertRowRenderer (default `null`) A function to customize grid inserting row. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### editRowRenderer (default `null`) A function to customize editing row rendering. The function signature is `function(item, itemIndex)`, where `item` is row data item, and `itemIndex` is the item index. The function should return markup as a string, jQueryElement or DomNode representing table row `tr`. ### pagerRenderer (default `null`) > version added: 1.2 A function to customize pager rendering. The function accepts a single argument with the following structure: ```javascript { pageIndex, // index of the currently opened page pageCount // total amount of grid pages } ``` The function should return markup as a string, jQueryElement or DomNode representing the pager. If `pagerRenderer` is specified, then `pagerFormat` option will be ignored. ## Grid Fields All fields supporting by grid are stored in `jsGrid.fields` object, where key is a type of the field and the value is the field class. `jsGrid.fields` contains following build-in fields: ```javascript { text: { ... }, // simple text input number: { ... }, // number input select: { ... }, // select control checkbox: { ... }, // checkbox input textarea: { ... }, // textarea control (renders textarea for inserting and editing and text input for filtering) control: { ... } // control field with delete and editing buttons for data rows, search and add buttons for filter and inserting row } ``` Each build-in field can be easily customized with general configuration properties described in [fields](#fields) section and custom field-specific properties described below. ### text Text field renders `<input type="text">` in filter, inserting and editing rows. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### number Number field renders `<input type="number">` in filter, inserting and editing rows. Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "right", // right text alignment readOnly: false // a boolean defines whether input is readonly (added in v1.4) } ``` ### select Select field renders `<select>` control in filter, inserting and editing rows. Custom properties: ```javascript { align: "center", // center text alignment autosearch: true, // triggers searching when the user changes the selected item in the filter items: [], // an array of items for select valueField: "", // name of property of item to be used as value textField: "", // name of property of item to be used as displaying value selectedIndex: -1, // index of selected item by default valueType: "number|string", // the data type of the value readOnly: false // a boolean defines whether select is readonly (added in v1.4) } ``` If valueField is not defined, then the item index is used instead. If textField is not defined, then item itself is used to display value. For instance the simple select field config may look like: ```javascript { name: "Country", type: "select", items: [ "", "United States", "Canada", "United Kingdom" ] } ``` or more complex with items as objects: ```javascript { name: "Country", type: "select" items: [ { Name: "", Id: 0 }, { Name: "United States", Id: 1 }, { Name: "Canada", Id: 2 }, { Name: "United Kingdom", Id: 3 } ], valueField: "Id", textField: "Name" } ``` `valueType` defines whether the field value should be converted to a number or returned as a string. The value of the option is determined automatically depending on the data type of `valueField` of the first item, but it can be overridden. ### checkbox Checkbox field renders `<input type="checkbox">` in filter, inserting and editing rows. Filter checkbox supports intermediate state for, so click switches between 3 states (checked|intermediate|unchecked). Custom properties: ```javascript { sorter: "number", // uses sorter for numbers align: "center", // center text alignment autosearch: true // triggers searching when the user clicks checkbox in filter } ``` ### textarea Textarea field renders `<textarea>` in inserting and editing rows and `<input type="text">` in filter row. Custom properties: ```javascript { autosearch: true, // triggers searching when the user presses `enter` key in the filter input readOnly: false // a boolean defines whether textarea is readonly (added in v1.4) } ``` ### control Control field renders delete and editing buttons in data row, search and add buttons in filter and inserting row accordingly. It also renders button switching between filtering and searching in header row. Custom properties: ```javascript { editButton: true, // show edit button deleteButton: true, // show delete button clearFilterButton: true, // show clear filter button modeSwitchButton: true, // show switching filtering/inserting button align: "center", // center content alignment width: 50, // default column width is 50px filtering: false, // disable filtering for column inserting: false, // disable inserting for column editing: false, // disable editing for column sorting: false, // disable sorting for column searchModeButtonTooltip: "Switch to searching", // tooltip of switching filtering/inserting button in inserting mode insertModeButtonTooltip: "Switch to inserting", // tooltip of switching filtering/inserting button in filtering mode editButtonTooltip: "Edit", // tooltip of edit item button deleteButtonTooltip: "Delete", // tooltip of delete item button searchButtonTooltip: "Search", // tooltip of search button clearFilterButtonTooltip: "Clear filter", // tooltip of clear filter button insertButtonTooltip: "Insert", // tooltip of insert button updateButtonTooltip: "Update", // tooltip of update item button cancelEditButtonTooltip: "Cancel edit", // tooltip of cancel editing button } ``` ### Custom Field If you need a completely custom field, the object `jsGrid.fields` can be easily extended. In this example we define new grid field `date`: ```javascript var MyDateField = function(config) { jsGrid.Field.call(this, config); }; MyDateField.prototype = new jsGrid.Field({ css: "date-field", // redefine general property 'css' align: "center", // redefine general property 'align' myCustomProperty: "foo", // custom property sorter: function(date1, date2) { return new Date(date1) - new Date(date2); }, itemTemplate: function(value) { return new Date(value).toDateString(); }, insertTemplate: function(value) { return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() }); }, editTemplate: function(value) { return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value)); }, insertValue: function() { return this._insertPicker.datepicker("getDate").toISOString(); }, editValue: function() { return this._editPicker.datepicker("getDate").toISOString(); } }); jsGrid.fields.date = MyDateField; ``` To have all general grid field properties custom field class should inherit `jsGrid.Field` class or any other field class. Here `itemTemplate` just returns the string representation of a date. `insertTemplate` and `editTemplate` create jQuery UI datePicker for inserting and editing row. Of course jquery ui library should be included to make it work. `insertValue` and `editValue` return date to insert and update items accordingly. We also defined date specific sorter. Now, our new field `date` can be used in the grid config as follows: ```javascript { fields: [ ... { type: "date", myCustomProperty: "bar" }, ... ] } ``` ## Methods jsGrid methods could be called with `jsGrid` jQuery plugin or directly. To use jsGrid plugin to call a method, just call `jsGrid` with method name and required parameters as next arguments: ```javascript // calling method with jQuery plugin $("#grid").jsGrid("methodName", param1, param2); ``` To call method directly you need to retrieve grid instance or just create grid with the constructor: ```javascript // retrieve grid instance from element data var grid = $("#grid").data("JSGrid"); // create grid with the constructor var grid = new jsGrid.Grid($("#grid"), { ... }); // call method directly grid.methodName(param1, param2); ``` ### cancelEdit() Cancels row editing. ```javascript $("#grid").jsGrid("cancelEdit"); ``` ### clearFilter(): `Promise` Clears current filter and performs search with empty filter. Returns jQuery promise resolved when data filtering is completed. ```javascript $("#grid").jsGrid("clearFilter").done(function() { console.log("filtering completed"); }); ``` ### clearInsert() Clears current inserting row. ```javascript $("#grid").jsGrid("clearInsert"); ``` ### deleteItem(item|$row|rowNode): `Promise` Removes specified row from the grid. Returns jQuery promise resolved when deletion is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // delete row by item reference $("#grid").jsGrid("deleteItem", item); // delete row by jQueryElement $("#grid").jsGrid("deleteItem", $(".specific-row")); // delete row by DomNode $("#grid").jsGrid("deleteItem", rowNode); ``` ### destroy() Destroys the grid and brings the Node to its original state. ```javascript $("#grid").jsGrid("destroy"); ``` ### editItem(item|$row|rowNode) Sets grid editing row. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. ```javascript // edit row by item reference $("#grid").jsGrid("editItem", item); // edit row by jQueryElement $("#grid").jsGrid("editItem", $(".specific-row")); // edit row by DomNode $("#grid").jsGrid("editItem", rowNode); ``` ### getFilter(): `Object` Get grid filter as a plain object. ```javascript var filter = $("#grid").jsGrid("getFilter"); ``` ### getSorting(): `Object` > version added: 1.2 Get grid current sorting params as a plain object with the following format: ```javascript { field, // the name of the field by which grid is sorted order // 'asc' or 'desc' depending on sort order } ``` ```javascript var sorting = $("#grid").jsGrid("getSorting"); ``` ### fieldOption(fieldName|fieldIndex, optionName, [optionValue]) > version added: 1.3 Gets or sets the value of a field option. **fieldName|fieldIndex** is the name or the index of the field to get/set the option value (if the grid contains more than one field with the same name, the first field will be used). **optionName** is the name of the field option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the field option `optionName` will be returned. ```javascript // hide the field "ClientName" $("#grid").jsGrid("fieldOption", "ClientName", "visible", false); // get width of the 2nd field var secondFieldOption = $("#grid").jsGrid("fieldOption", 1, "width"); ``` ### insertItem([item]): `Promise` Inserts row into the grid based on item. Returns jQuery promise resolved when insertion is completed. **item** is the item to pass to `controller.insertItem`. If `item` is not specified the data from inserting row will be inserted. ```javascript // insert item from inserting row $("#grid").jsGrid("insertItem"); // insert item $("#grid").jsGrid("insertItem", { Name: "John", Age: 25, Country: 2 }).done(function() { console.log("insertion completed"); }); ``` ### loadData([filter]): `Promise` Loads data calling corresponding `controller.loadData` method. Returns jQuery promise resolved when data loading is completed. It preserves current sorting and paging unlike the `search` method . **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // load data with current grid filter $("#grid").jsGrid("loadData"); // loadData with custom filter $("#grid").jsGrid("loadData", { Name: "John" }).done(function() { console.log("data loaded"); }); ``` ### exportData([options]) Transforms the grid data into the specified output type. Output can be formatted, filtered or modified by providing options. Currently only supports CSV output. ```javascript //Basic export var csv = $("#grid").jsGrid("exportData"); //Full Options var csv = $("#grid").jsGrid("exportData", { type: "csv", //Only CSV supported subset: "all" | "visible", //Visible will only output the currently displayed page delimiter: "|", //If using csv, the character to seperate fields includeHeaders: true, //Include header row in output encapsulate: true, //Surround each field with qoutation marks; needed for some systems newline: "\r\n", //Newline character to use //Takes each item and returns true if it should be included in output. //Executed only on the records within the given subset above. filter: function(item){return true}, //Transformations are a way to modify the display value of the output. //Provide a key of the field name, and a function that takes the current value. transformations: { "Married": function(value){ if (value === true) return "Yes" if (value !== false) return "No" } } }); ``` ### openPage(pageIndex) Opens the page of specified index. **pageIndex** is one-based index of the page to open. The value should be in range from 1 to [total amount of pages]. ### option(optionName, [optionValue]) Gets or sets the value of an option. **optionName** is the name of the option. **optionValue** is the new option value to set. If `optionValue` is not specified, then the value of the option `optionName` will be returned. ```javascript // turn off paging $("#grid").jsGrid("option", "paging", false); // get current page index var pageIndex = $("#grid").jsGrid("option", "pageIndex"); ``` ### refresh() Refreshes the grid. Renders the grid body and pager content, recalculates sizes. ```javascript $("#grid").jsGrid("refresh"); ``` ### render(): `Promise` Performs complete grid rendering. If option `autoload` is `true` calls `controller.loadData`. The state of the grid like current page and sorting is retained. Returns jQuery promise resolved when data loading is completed. If auto-loading is disabled the promise is instantly resolved. ```javascript $("#grid").jsGrid("render").done(function() { console.log("rendering completed and data loaded"); }); ``` ### reset() Resets the state of the grid. Goes to the first data page, resets sorting, and then calls `refresh`. ```javascript $("#grid").jsGrid("reset"); ``` ### rowByItem(item): `jQueryElement` > version added: 1.3 Gets the row jQuery element corresponding to the item. **item** is the item corresponding to the row. ```javascript var $row = $("#grid").jsGrid("rowByItem", item); ``` ### search([filter]): `Promise` Performs filtering of the grid. Returns jQuery promise resolved when data loading is completed. It resets current sorting and paging unlike the `loadData` method. **filter** is a filter to pass to `controller.loadData`. If `filter` is not specified the current filter (filtering row values) will be applied. ```javascript // search with current grid filter $("#grid").jsGrid("search"); // search with custom filter $("#grid").jsGrid("search", { Name: "John" }).done(function() { console.log("filtering completed"); }); ``` ### showPrevPages() Shows previous set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showPrevPages"); ``` ### showNextPages() Shows next set of pages, when total amount of pages more than `pageButtonCount`. ```javascript $("#grid").jsGrid("showNextPages"); ``` ### sort(sortConfig|field, [order]): `Promise` Sorts grid by specified field. Returns jQuery promise resolved when sorting is completed. **sortConfig** is the plain object of the following structure `{ field: (fieldIndex|fieldName|field), order: ("asc"|"desc") }` **field** is the field to sort by. It could be zero-based field index or field name or field reference **order** is the sorting order. Accepts the following values: "asc"|"desc" If `order` is not specified, then data is sorted in the reversed to current order, when grid is already sorted by the same field. Or `"asc"` for sorting by another field. When grid data is loaded by pages (`pageLoading` is `true`) sorting calls `controller.loadData` with sorting parameters. Read more in [Grid Controller](#grid-controller) section. ```javascript // sorting grid by first field $("#grid").jsGrid("sort", 0); // sorting grid by field "Name" in descending order $("#grid").jsGrid("sort", { field: "Name", order: "desc" }); // sorting grid by myField in ascending order $("#grid").jsGrid("sort", myField, "asc").done(function() { console.log("sorting completed"); }); ``` ### updateItem([item|$row|rowNode], [editedItem]): `Promise` Updates item and row of the grid. Returns jQuery promise resolved when update is completed. **item|$row|rowNode** is the reference to the item or the row jQueryElement or the row DomNode. **editedItem** is the changed item to pass to `controller.updateItem`. If `item|$row|rowNode` is not specified then editing row will be updated. If `editedItem` is not specified the data from editing row will be taken. ```javascript // update currently editing row $("#grid").jsGrid("updateItem"); // update currently editing row with specified data $("#grid").jsGrid("updateItem", { ID: 1, Name: "John", Age: 25, Country: 2 }); // update specified item with particular data (row DomNode or row jQueryElement can be used instead of item reference) $("#grid").jsGrid("updateItem", item, { ID: 1, Name: "John", Age: 25, Country: 2 }).done(function() { console.log("update completed"); }); ``` ### jsGrid.locale(localeName|localeConfig) > version added: 1.4 Set current locale of all grids. **localeName|localeConfig** is the name of the supported locale (see [available locales](src/i18n)) or a custom localization config. Find more information on custom localization config in [Localization](#localization). ```javascript // set French locale jsGrid.locale("fr"); ``` ### jsGrid.setDefaults(config) Set default options for all grids. ```javascript jsGrid.setDefaults({ filtering: true, inserting: true }); ``` ### jsGrid.setDefaults(fieldName, config) Set default options of the particular field. ```javascript jsGrid.setDefaults("text", { width: 150, css: "text-field-cls" }); ``` ## Callbacks jsGrid allows to specify a callback function to be executed on a particular event. The following callbacks are supported: ```javascript { onDataLoading: function(args) {}, // before controller.loadData onDataLoaded: function(args) {}, // on done of controller.loadData onDataExporting: function() {}, // before data export onInit: function(args) {}, // after grid initialization onItemInserting: function(args) {}, // before controller.insertItem onItemInserted: function(args) {}, // on done of controller.insertItem onItemUpdating: function(args) {}, // before controller.updateItem onItemUpdated: function(args) {}, // on done of controller.updateItem onItemDeleting: function(args) {}, // before controller.deleteItem onItemDeleted: function(args) {}, // on done of controller.deleteItem onItemInvalid: function(args) {}, // after item validation, in case data is invalid onError: function(args) {}, // on fail of any controller call onOptionChanging: function(args) {}, // before changing the grid option onOptionChanged: function(args) {}, // after changing the grid option onPageChanged: function(args) {}, // after changing the current page onRefreshing: function(args) {}, // before grid refresh onRefreshed: function(args) {}, // after grid refresh } ``` ### onDataLoading Fires before data loading. Has the following arguments: ```javascript { grid // grid instance filter // loading filter object } ``` #### Cancel Data Loading > version added: 1.2 To cancel data loading set `args.cancel = true`. In the following example loading is canceled when the filter has empty 'name' field: ```javascript $("#grid").jsGrid({ ... onDataLoading: function(args) { // cancel loading data if 'name' is empty if(args.filter.name === "") { args.cancel = true; } } }); ``` ### onDataLoaded Fires after data loading. Has the following arguments: ```javascript { grid // grid instance data // load result (array of items or data structure for loading by page scenario) } ``` In the following example the loaded data is written to the browser console. ```javascript $("#grid").jsGrid({ ... onDataLoaded: function(args) { console.log(args.data); } }); ``` ### onInit > version added: 1.5 Fires after grid initialization right before rendering. Usually used to get grid instance. Has the following arguments: ```javascript { grid // grid instance } ``` In the following example we get the grid instance on initialization: ```javascript var gridInstance; $("#grid").jsGrid({ ... onInit: function(args) { gridInstance = args.grid; } }); ``` ### onError Fires when controller handler promise failed. Has the following arguments: ```javascript { grid // grid instance args // an array of arguments provided to fail promise handler } ``` ### onItemDeleting Fires before item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleting row jQuery element item // deleting item itemIndex // deleting item index } ``` #### Cancel Item Deletion > version added: 1.2 To cancel item deletion set `args.cancel = true`. This allows to do a validation before performing the actual deletion. In the following example the deletion of items marked as `protected` is canceled: ```javascript $("#grid").jsGrid({ ... onItemDeleting: function(args) { // cancel deletion of the item with 'protected' field if(args.item.protected) { args.cancel = true; } } }); ``` ### onItemDeleted Fires after item deletion. Has the following arguments: ```javascript { grid // grid instance row // deleted row jQuery element item // deleted item itemIndex // deleted item index } ``` ### onItemEditing > version added: 1.4 Fires before item editing. Has the following arguments: ```javascript { grid // grid instance row // editing row jQuery element item // editing item itemIndex // editing item index } ``` #### Cancel Item Editing To cancel item editing set `args.cancel = true`. This allows to prevent row from editing conditionally. In the following example the editing of the row for item with 'ID' = 0 is canceled: ```javascript $("#grid").jsGrid({ ... onItemEditing: function(args) { // cancel editing of the row of item with field 'ID' = 0 if(args.item.ID === 0) { args.cancel = true; } } }); ``` ### onItemInserting Fires before item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserting item } ``` #### Cancel Item Insertion > version added: 1.2 To cancel item insertion set `args.cancel = true`. This allows to do a validation before performing the actual insertion. In the following example insertion of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemInserting: function(args) { // cancel insertion of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemInserted Fires after item insertion. Has the following arguments: ```javascript { grid // grid instance item // inserted item } ``` ### onItemInvalid Fired when item is not following validation rules on inserting or updating. Has the following arguments: ```javascript { grid // grid instance row // inserting/editing row jQuery element item // inserting/editing item itemIndex // inserting/editing item index errors // array of validation violations in format { field: "fieldName", message: "validator message" } } ``` The following handler prints errors on the console ```javascript $("#grid").jsGrid({ ... onItemInvalid: function(args) { // prints [{ field: "Name", message: "Enter client name" }] console.log(args.errors); } }); ``` ### onItemUpdating Fires before item update. Has the following arguments: ```javascript { grid // grid instance row // updating row jQuery element item // updating item itemIndex // updating item index previousItem // shallow copy (not deep copy) of item before editing } ``` #### Cancel Item Update > version added: 1.2 To cancel item update set `args.cancel = true`. This allows to do a validation before performing the actual update. In the following example update of items with the 'name' specified is allowed: ```javascript $("#grid").jsGrid({ ... onItemUpdating: function(args) { // cancel update of the item with empty 'name' field if(args.item.name === "") { args.cancel = true; alert("Specify the name of the item!"); } } }); ``` ### onItemUpdated Fires after item update. Has the following arguments: ```javascript { grid // grid instance row // updated row jQuery element item // updated item itemIndex // updated item index previousItem // shallow copy (not deep copy) of item before editing } ``` ### onOptionChanging Fires before grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of option to be changed oldValue // old value of option newValue // new value of option } ``` ### onOptionChanged Fires after grid option value change. Has the following arguments: ```javascript { grid // grid instance option // name of changed option value // changed option value } ``` ### onPageChanged > version added: 1.5 Fires once grid current page index is changed. It happens either by switching between the pages with the pager links, or by calling the method `openPage`, or changing the option `pageIndex`. Has the following arguments: ```javascript { grid // grid instance pageIndex // current page index } ``` In the following example we print the current page index in the browser console once it has been changed: ```javascript $("#grid").jsGrid({ ... onPageChanged: function(args) { console.log(args.pageIndex); } }); ``` ### onRefreshing Fires before grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ### onRefreshed Fires after grid refresh. Has the following arguments: ```javascript { grid // grid instance } ``` ## Grid Controller The controller is a gateway between grid and data storage. All data manipulations call accordant controller methods. By default grid has an empty controller and can work with static array of items stored in option `data`. A controller should implement the following methods: ```javascript { loadData: function(filter) { ... }, insertItem: function(item) { ... }, updateItem: function(item) { ... }, deleteItem: function(item) { ... } } ``` Asynchronous controller methods should return a Promise, resolved once the request is completed. Starting v1.5 jsGrid supports standard JavaScript Promise/A, earlier versions support only jQuery.Promise. For instance the controller for typical REST service might look like: ```javascript { loadData: function(filter) { return $.ajax({ type: "GET", url: "/items", data: filter }); }, insertItem: function(item) { return $.ajax({ type: "POST", url: "/items", data: item }); }, updateItem: function(item) { return $.ajax({ type: "PUT", url: "/items", data: item }); }, deleteItem: function(item) { return $.ajax({ type: "DELETE", url: "/items", data: item }); }, } ``` ### loadData(filter): `Promise|dataResult` Called on data loading. **filter** contains all filter parameters of fields with enabled filtering When `pageLoading` is `true` and data is loaded by page, `filter` includes two more parameters: ```javascript { pageIndex // current page index pageSize // the size of page } ``` When grid sorting is enabled, `filter` includes two more parameters: ```javascript { sortField // the name of sorting field sortOrder // the order of sorting as string "asc"|"desc" } ``` Method should return `dataResult` or jQuery promise that will be resolved with `dataResult`. **dataResult** depends on `pageLoading`. When `pageLoading` is `false` (by default), then data result is a plain javascript array of objects. If `pageLoading` is `true` data result should have following structure ```javascript { data // array of items itemsCount // total items amount in storage } ``` ### insertItem(item): `Promise|insertedItem` Called on item insertion. Method should return `insertedItem` or jQuery promise that will be resolved with `insertedItem`. If no item is returned, inserting item will be used as inserted item. **item** is the item to be inserted. ### updateItem(item): `Promise|updatedItem` Called on item update. Method should return `updatedItem` or jQuery promise that will be resolved with `updatedItem`. If no item is returned, updating item will be used as updated item. **item** is the item to be updated. ### deleteItem(item): `Promise` Called on item deletion. If deletion is asynchronous, method should return jQuery promise that will be resolved when deletion is completed. **item** is the item to be deleted. ## Validation > version added: 1.4 ### Field Validation Config `validate` option of the field can have 4 different value types `string|Object|Array|function`: 1. `validate: "validatorName"` **validatorName** - is a string key of the validator in the `jsGrid.validators` registry. The registry can be easily extended. See available [built-in validators here](#built-in-validators). In the following example the `required` validator is applied: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "FieldName", validate: "required" }] }); ``` 2. `validate: validationConfig` **validateConfig** - is a plain object of the following structure: ```javascript { validator: string|function(value, item, param), // built-in validator name or custom validation function message: string|function, // validation message or a function(value, item) returning validation message param: any // a plain object with parameters to be passed to validation function } ``` In the following example the `range` validator is applied with custom validation message and range provided in parameters: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: { validator: "range", message: function(value, item) { return "The client age should be between 21 and 80. Entered age is \"" + value + "\" is out of specified range."; }, param: [21, 80] } }] }); ``` 3. `validate: validateArray` **validateArray** - is an array of validators. It can contain * `string` - validator name * `Object` - validator configuration of structure `{ validator, message, param }` * `function` - validation function as `function(value, item)` In the following example the field has three validators: `required`, `range`, and a custom function validator: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "number", name: "Age", validate: [ "required", { validator: "range", param: [21, 80] }, function(value, item) { return item.IsRetired ? value > 55 : true; } ] }] }); ``` 4. `validate: function(value, item, param)` The parameters of the function: * `value` - entered value of the field * `item` - editing/inserting item * `param` - a parameter provided by validator (applicable only when validation config is defined at validation object or an array of objects) In the following example the field has custom validation function: ```javascript $("#grid").jsGrid({ ... fields: [{ type: "text", name: "Phone", validate: function(value, item) { return value.length == 10 && phoneBelongsToCountry(value, item.Country); } }] }); ``` ### Built-in Validators The `jsGrid.validators` object contains all built-in validators. The key of the hash is a validator name and the value is the validator config. `jsGrid.validators` contains the following build-in validators: * **required** - the field value is required * **rangeLength** - the length of the field value is limited by range (the range should be provided as an array in `param` field of validation config) * **minLength** - the minimum length of the field value is limited (the minimum value should be provided in `param` field of validation config) * **maxLength** - the maximum length of the field value is limited (the maximum value should be provided in `param` field of validation config) * **pattern** - the field value should match the defined pattern (the pattern should be provided as a regexp literal or string in `param` field of validation config) * **range** - the value of the number field is limited by range (the range should be provided as an array in `param` field of validation config) * **min** - the minimum value of the number field is limited (the minimum should be provided in `param` field of validation config) * **max** - the maximum value of the number field is limited (the maximum should be provided in `param` field of validation config) ### Custom Validators To define a custom validator just add it to the `jsGrid.validators` object. In the following example a custom validator `time` is registered: ```javascript jsGrid.validators.time = { message: "Please enter a valid time, between 00:00 and 23:59", validator: function(value, item) { return /^([01]\d|2[0-3]|[0-9])(:[0-5]\d){1,2}$/.test(value); } } ``` ## Localization > version added: 1.4 Current locale can be set for all grids on the page with the [`jsGrid.locale(localeName)`](#jsgridlocalelocalenamelocaleconfig) method. New custom locale can be added to `jsGrid.locales` hash like the following: ```javascript jsGrid.locales.my_lang = { // localization config goes here ... }; ``` Here is how localization config looks like for Spanish [i18n/es.js](src/i18n/es.js). Find all available locales [here](src/i18n). ## Sorting Strategies All supported sorting strategies are stored in `jsGrid.sortStrategies` object, where key is a name of the strategy and the value is a `sortingFunction`. `jsGrid.sortStrategies` contains following build-in sorting strategies: ```javascript { string: { ... }, // string sorter number: { ... }, // number sorter date: { ... }, // date sorter numberAsString: { ... } // numbers are parsed before comparison } ``` **sortingFunction** is a sorting function with the following format: ```javascript function(value1, value2) { if(value1 < value2) return -1; // return negative value when first is less than second if(value1 === value2) return 0; // return zero if values are equal if(value1 > value2) return 1; // return positive value when first is greater than second } ``` ### Custom Sorting Strategy If you need a custom sorting strategy, the object `jsGrid.sortStrategies` can be easily extended. In this example we define new sorting strategy for our client objects: ```javascript // clients array var clients = [{ Index: 1, Name: "John", Age: 25 }, ...]; // sort clients by name and then by age jsGrid.sortStrategies.client = function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; }; ``` Now, our new sorting strategy `client` can be used in the grid config as follows: ```javascript { fields: [ ... { name: "Index", sorter: "client" }, ... ] } ``` Worth to mention, that if you need particular sorting only once, you can just inline sorting function in `sorter` not registering the new strategy: ```javascript { fields: [ ... { name: "Index", sorter: function(index1, index2) { var client1 = clients[index1]; var client2 = clients[index2]; return client1.Name.localeCompare(client2.Name) || client1.Age - client2.Age; } }, ... ] } ``` ## Load Strategies The behavior of the grid regarding data source interaction is defined by load strategy. The load strategy has the following methods: ```javascript { firstDisplayIndex: function() {}, // returns the index of the first displayed item lastDisplayIndex: function() {}, // returns the index of the last displayed item itemsCount: function() {}, // returns the total amount of grid items openPage: function(index) {}, // handles opening of the particular page loadParams: function() {}, // returns additional parameters for controller.loadData method sort: function() {}, // handles sorting of data in the grid, should return a Promise reset: function() {}, // handles grid refresh on grid reset with 'reset' method call, should return a Promise finishLoad: function(loadedData) {}, // handles the finish of loading data by controller.loadData finishInsert: function(insertedItem) {}, // handles the finish of inserting item by controller.insertItem finishDelete: function(deletedItem, deletedItemIndex) {} // handles the finish of deleting item by controller.deleteItem } ``` There are two build-in load strategies: DirectLoadingStrategy (for `pageLoading=false`) and PageLoadingStrategy (for `pageLoading=true`). ### DirectLoadingStrategy **DirectLoadingStrategy** is used when loading by page is turned off (`pageLoading=false`). It provides the following behavior: - **firstDisplayIndex** returns the index of the first item on the displayed page - **lastDisplayIndex** returns the index of the last item on the displayed page - **itemsCount** returns the actual amount of all the loaded items - **openPage** refreshes the grid to render items of current page - **loadParams** returns empty object, since no extra load params are needed - **sort** sorts data items and refreshes the grid calling `grid.refresh` - **reset** calls `grid.refresh` method to refresh the grid - **finishLoad** puts the data coming from `controller.loadData` into the option `data` of the grid - **finishInsert** pushes new inserted item into the option `data` and refreshes the grid - **finishDelete** removes deleted item from the option `data` and resets the grid ### PageLoadingStrategy **PageLoadingStrategy** is used when data is loaded to the grid by pages (`pageLoading=true`). It provides the following behavior: - **firstDisplayIndex** returns 0, because all loaded items displayed on the current page - **lastDisplayIndex** returns the amount of loaded items, since data loaded by page - **itemsCount** returns `itemsCount` provided by `controller.loadData` (read more in section [controller.loadData](#loaddatafilter-promisedataresult)) - **openPage** calls `grid.loadData` to load data for the current page - **loadParams** returns an object with the structure `{ pageIndex, pageSize }` to provide server with paging info - **sort** calls `grid.loadData` to load sorted data from the server - **reset** calls `grid.loadData` method to refresh the data - **finishLoad** saves `itemsCount` returned by server and puts the `data` into the option `data` of the grid - **finishInsert** calls `grid.search` to reload the data - **finishDelete** calls `grid.search` to reload the data ### Custom LoadStrategy The option `loadStrategy` allows to specify a custom load strategy to customize the behavior of the grid. The easiest way to do it is to inherit from existing strategy. By default DirectLoadingStrategy resets the grid (resets the paging and sorting) when an item is deleted. The following example shows how to create a custom strategy to avoid grid reset on deletion of an item. ```javascript var MyCustomDirectLoadStrategy = function(grid) { jsGrid.loadStrategies.DirectLoadingStrategy.call(this, grid); }; MyCustomDirectLoadStrategy.prototype = new jsGrid.loadStrategies.DirectLoadingStrategy(); MyCustomDirectLoadStrategy.prototype.finishDelete = function(deletedItem, deletedItemIndex) { var grid = this._grid; grid.option("data").splice(deletedItemIndex, 1); grid.refresh(); }; // use custom strategy in grid config $("#grid").jsGrid({ loadStrategy: function() { return new MyCustomDirectLoadStrategy(this); }, ... }); ``` ## Load Indication By default jsGrid uses jsGrid.LoadIndicator. Load indicator can be customized with the `loadIndicator` option. Set an object or a function returning an object supporting the following interface: ```javascript { show: function() { ... } // called on loading start hide: | 4 | README: Fixed example which contained invalid logic | 2 | .md | md | mit | tabalinas/jsgrid |
10067854 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067855 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067856 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067857 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067858 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067859 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067860 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067861 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067862 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067863 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067864 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067865 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067866 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067867 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067868 | <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;
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
private readonly TMModel _model;
private Dictionary<int, IBrush> _brushes;
public TextMateColoringTransformer(TMModel model)
{
_brushes = new Dictionary<int, IBrush>();
_model = model;
}
public void SetTheme(Theme theme)
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)
public void SetGrammar(IGrammar grammar)
{
_model.SetGrammar(grammar);
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
var tokens = _model.GetLineTokens(line.LineNumber - 1);
if (tokens is { })
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? line.Length;
if (startIndex == endIndex || token.type == string.Empty)
{
continue;
}
var themeRules = _theme.Match(token.type);
foreach (var themeRule in themeRules)
{
if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
{
SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
}
}
}
var id = _theme.GetColorId(color);
_brushes[id] = new ImmutableSolidColorBrush(Color.Parse(NormalizeColor(color)));
}
}
public void SetGrammar(IGrammar grammar)
{
_grammar = grammar;
if (_model != null)
{
_model.SetGrammar(grammar);
}
}
IBrush ForegroundTextTransformation.IColorMap.GetBrush(int colorId)
{
if (_brushes == null)
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);
}
}
finally
{
ArrayPool<ForegroundTextTransformation>.Shared.Return(transformsInLine);
}
}
catch (Exception ex)
{
_exceptionHandler?.Invoke(ex);
}
}
private void GetLineTransformations(int lineNumber, List<TMToken> tokens, ForegroundTextTransformation[] transformations)
{
for (int i = 0; i < tokens.Count; i++)
{
var token = tokens[i];
var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
var startIndex = token.StartIndex;
var endIndex = nextToken?.StartIndex ?? _model.GetLines().GetLineLength(lineNumber - 1);
if (startIndex >= endIndex || token.Scopes == null || token.Scopes.Count == 0)
{
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> re-color when changing document.
<DFF> @@ -11,13 +11,24 @@ namespace AvaloniaEdit.TextMate
public class TextMateColoringTransformer : GenericLineTransformer
{
private Theme _theme;
- private readonly TMModel _model;
+ private IGrammar _grammar;
+ private TMModel _model;
+
private Dictionary<int, IBrush> _brushes;
- public TextMateColoringTransformer(TMModel model)
+ public TextMateColoringTransformer()
{
_brushes = new Dictionary<int, IBrush>();
+ }
+
+ public void SetModel(TMModel model)
+ {
_model = model;
+
+ if (_grammar != null)
+ {
+ _model.SetGrammar(_grammar);
+ }
}
public void SetTheme(Theme theme)
@@ -38,35 +49,43 @@ namespace AvaloniaEdit.TextMate
public void SetGrammar(IGrammar grammar)
{
- _model.SetGrammar(grammar);
+ _grammar = grammar;
+
+ if (_model != null)
+ {
+ _model.SetGrammar(grammar);
+ }
}
protected override void TransformLine(DocumentLine line, ITextRunConstructionContext context)
{
- var tokens = _model.GetLineTokens(line.LineNumber - 1);
-
- if (tokens is { })
+ if (_model is { })
{
- for (int i = 0; i < tokens.Count; i++)
+ var tokens = _model.GetLineTokens(line.LineNumber - 1);
+
+ if (tokens is { })
{
- var token = tokens[i];
- var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
+ for (int i = 0; i < tokens.Count; i++)
+ {
+ var token = tokens[i];
+ var nextToken = (i + 1) < tokens.Count ? tokens[i + 1] : null;
- var startIndex = token.StartIndex;
- var endIndex = nextToken?.StartIndex ?? line.Length;
+ var startIndex = token.StartIndex;
+ var endIndex = nextToken?.StartIndex ?? line.Length;
- if (startIndex == endIndex || token.type == string.Empty)
- {
- continue;
- }
+ if (startIndex == endIndex || token.type == string.Empty)
+ {
+ continue;
+ }
- var themeRules = _theme.Match(token.type);
+ var themeRules = _theme.Match(token.type);
- foreach (var themeRule in themeRules)
- {
- if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ foreach (var themeRule in themeRules)
{
- SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ if (themeRule.foreground > 0 && _brushes.ContainsKey(themeRule.foreground))
+ {
+ SetTextStyle(line, startIndex, endIndex - startIndex, _brushes[themeRule.foreground]);
+ }
}
}
}
| 39 | re-color when changing document. | 20 | .cs | TextMate/TextMateColoringTransformer | mit | AvaloniaUI/AvaloniaEdit |
10067869 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067870 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067871 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067872 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067873 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067874 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067875 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067876 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067877 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067878 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067879 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067880 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067881 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067882 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067883 | <NME> ChangeDocumentTests.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.Text;
using AvaloniaEdit.AvaloniaMocks;
using AvaloniaEdit.Document;
using NUnit.Framework;
namespace AvaloniaEdit.Editing
{
[TestFixture]
public class ChangeDocumentTests
{
[Test]
public void ClearCaretAndSelectionOnDocumentChange()
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = new TextDocument("1\n2nd");
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
textArea.Caret.Offset = 6;
textArea.Selection = Selection.Create(textArea, 3, 6);
textArea.Document = null;
Assert.AreEqual(0, textArea.Caret.Offset);
Assert.AreEqual(new TextLocation(1, 1), textArea.Caret.Location);
Assert.IsTrue(textArea.Selection.IsEmpty);
}
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
platform: new MockRuntimePlatform())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration(),
fontManagerImpl: new MockFontManagerImpl(),
textShaperImpl: new MockTextShaperImpl())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
StringBuilder b = new StringBuilder();
textArea.TextView.DocumentChanged += delegate
{
b.Append("TextView.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.DocumentChanged += delegate
{
b.Append("TextArea.DocumentChanged;");
Assert.AreSame(newDocument, textArea.TextView.Document);
Assert.AreSame(newDocument, textArea.Document);
};
textArea.Document = newDocument;
Assert.AreEqual("TextView.DocumentChanged;TextArea.DocumentChanged;", b.ToString());
}
}
}
}
<MSG> Fixed failing NUnit tests
Failed when PR https://github.com/AvaloniaUI/AvaloniaEdit/pull/161 was merged.
<DFF> @@ -31,7 +31,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -49,7 +50,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
textArea.Document = new TextDocument("1\n2\n3\n4th line");
@@ -67,7 +69,8 @@ namespace AvaloniaEdit.Editing
{
using (UnitTestApplication.Start(new TestServices(
renderInterface: new MockPlatformRenderInterface(),
- platform: new MockRuntimePlatform())))
+ platform: new MockRuntimePlatform(),
+ platformHotkeyConfiguration: new MockPlatformHotkeyConfiguration())))
{
TextArea textArea = new TextArea();
TextDocument newDocument = new TextDocument();
| 6 | Fixed failing NUnit tests | 3 | .cs | Tests/Editing/ChangeDocumentTests | mit | AvaloniaUI/AvaloniaEdit |
10067884 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067885 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067886 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067887 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067888 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067889 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067890 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067891 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067892 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067893 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067894 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067895 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067896 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067897 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067898 | <NME> TextView.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.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Threading.Tasks;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Controls.Documents;
using Avalonia.Controls.Primitives;
using Avalonia.Data;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Media.Immutable;
using Avalonia.Media.TextFormatting;
using Avalonia.Threading;
using Avalonia.VisualTree;
using AvaloniaEdit.Document;
using AvaloniaEdit.Editing;
using AvaloniaEdit.Utils;
namespace AvaloniaEdit.Rendering
{
/// <summary>
/// A virtualizing panel producing+showing <see cref="VisualLine"/>s for a <see cref="TextDocument"/>.
///
/// This is the heart of the text editor, this class controls the text rendering process.
///
/// Taken as a standalone control, it's a text viewer without any editing capability.
/// </summary>
[SuppressMessage("Microsoft.Design", "CA1001:TypesThatOwnDisposableFieldsShouldBeDisposable",
Justification = "The user usually doesn't work with TextView but with TextEditor; and nulling the Document property is sufficient to dispose everything.")]
public class TextView : Control, ITextEditorComponent, ILogicalScrollable
{
private EventHandler _scrollInvalidated;
#region Constructor
static TextView()
{
ClipToBoundsProperty.OverrideDefaultValue<TextView>(true);
FocusableProperty.OverrideDefaultValue<TextView>(false);
OptionsProperty.Changed.Subscribe(OnOptionsChanged);
DocumentProperty.Changed.Subscribe(OnDocumentChanged);
}
private readonly ColumnRulerRenderer _columnRulerRenderer;
private readonly CurrentLineHighlightRenderer _currentLineHighlighRenderer;
/// <summary>
/// Creates a new TextView instance.
/// </summary>
public TextView()
{
Services.AddService(this);
TextLayer = new TextLayer(this);
_elementGenerators = new ObserveAddRemoveCollection<VisualLineElementGenerator>(ElementGenerator_Added, ElementGenerator_Removed);
_lineTransformers = new ObserveAddRemoveCollection<IVisualLineTransformer>(LineTransformer_Added, LineTransformer_Removed);
_backgroundRenderers = new ObserveAddRemoveCollection<IBackgroundRenderer>(BackgroundRenderer_Added, BackgroundRenderer_Removed);
_columnRulerRenderer = new ColumnRulerRenderer(this);
_currentLineHighlighRenderer = new CurrentLineHighlightRenderer(this);
Options = new TextEditorOptions();
Debug.Assert(_singleCharacterElementGenerator != null); // assert that the option change created the builtin element generators
Layers = new LayerCollection(this);
InsertLayer(TextLayer, KnownLayer.Text, LayerInsertionPosition.Replace);
_hoverLogic = new PointerHoverLogic(this);
_hoverLogic.PointerHover += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverEvent, PointerHoverEvent);
_hoverLogic.PointerHoverStopped += (sender, e) => RaiseHoverEventPair(e, PreviewPointerHoverStoppedEvent, PointerHoverStoppedEvent);
}
#endregion
#region Document Property
/// <summary>
/// Document property.
/// </summary>
public static readonly StyledProperty<TextDocument> DocumentProperty =
AvaloniaProperty.Register<TextView, TextDocument>("Document");
private TextDocument _document;
private HeightTree _heightTree;
/// <summary>
/// Gets/Sets the document displayed by the text editor.
/// </summary>
public TextDocument Document
{
get => GetValue(DocumentProperty);
set => SetValue(DocumentProperty, value);
}
internal double FontSize
{
get => GetValue(TemplatedControl.FontSizeProperty);
set => SetValue(TemplatedControl.FontSizeProperty, value);
}
internal FontFamily FontFamily
{
get => GetValue(TemplatedControl.FontFamilyProperty);
set => SetValue(TemplatedControl.FontFamilyProperty, value);
}
/// <summary>
/// Occurs when the document property has changed.
/// </summary>
public event EventHandler DocumentChanged;
private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue);
}
private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue)
{
if (oldValue != null)
{
_heightTree.Dispose();
_heightTree = null;
_formatter = null;
CachedElements = null;
TextDocumentWeakEventManager.Changing.RemoveHandler(oldValue, OnChanging);
}
_document = newValue;
ClearScrollData();
ClearVisualLines();
if (newValue != null)
{
TextDocumentWeakEventManager.Changing.AddHandler(newValue, OnChanging);
_formatter = TextFormatter.Current;
InvalidateDefaultTextMetrics(); // measuring DefaultLineHeight depends on formatter
_heightTree = new HeightTree(newValue, DefaultLineHeight);
CachedElements = new TextViewCachedElements();
}
InvalidateMeasure();
DocumentChanged?.Invoke(this, EventArgs.Empty);
}
private void RecreateCachedElements()
{
if (CachedElements != null)
{
CachedElements = new TextViewCachedElements();
}
}
private void OnChanging(object sender, DocumentChangeEventArgs e)
{
Redraw(e.Offset, e.RemovalLength);
}
private void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
OnOptionChanged(e);
}
#endregion
#region Options property
/// <summary>
/// Options property.
/// </summary>
public static readonly StyledProperty<TextEditorOptions> OptionsProperty =
AvaloniaProperty.Register<TextView, TextEditorOptions>("Options");
/// <summary>
/// Gets/Sets the options used by the text editor.
/// </summary>
public TextEditorOptions Options
{
get => GetValue(OptionsProperty);
set => SetValue(OptionsProperty, value);
}
/// <summary>
/// Occurs when a text editor option has changed.
/// </summary>
public event PropertyChangedEventHandler OptionChanged;
/// <summary>
/// Raises the <see cref="OptionChanged"/> event.
/// </summary>
protected virtual void OnOptionChanged(PropertyChangedEventArgs e)
{
OptionChanged?.Invoke(this, e);
if (Options.ShowColumnRulers)
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
else
_columnRulerRenderer.SetRuler(null, ColumnRulerPen);
UpdateBuiltinElementGeneratorsFromOptions();
Redraw();
}
private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e)
{
(e.Sender as TextView)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue);
}
private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue)
{
if (oldValue != null)
{
PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChanged);
}
if (newValue != null)
{
PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChanged);
}
OnOptionChanged(new PropertyChangedEventArgs(null));
}
#endregion
#region ElementGenerators+LineTransformers Properties
private readonly ObserveAddRemoveCollection<VisualLineElementGenerator> _elementGenerators;
/// <summary>
/// Gets a collection where element generators can be registered.
/// </summary>
public IList<VisualLineElementGenerator> ElementGenerators => _elementGenerators;
private void ElementGenerator_Added(VisualLineElementGenerator generator)
{
ConnectToTextView(generator);
Redraw();
}
private void ElementGenerator_Removed(VisualLineElementGenerator generator)
{
DisconnectFromTextView(generator);
Redraw();
}
private readonly ObserveAddRemoveCollection<IVisualLineTransformer> _lineTransformers;
/// <summary>
/// Gets a collection where line transformers can be registered.
/// </summary>
public IList<IVisualLineTransformer> LineTransformers => _lineTransformers;
private void LineTransformer_Added(IVisualLineTransformer lineTransformer)
{
ConnectToTextView(lineTransformer);
Redraw();
}
private void LineTransformer_Removed(IVisualLineTransformer lineTransformer)
{
DisconnectFromTextView(lineTransformer);
Redraw();
}
#endregion
#region Builtin ElementGenerators
// NewLineElementGenerator newLineElementGenerator;
private SingleCharacterElementGenerator _singleCharacterElementGenerator;
private LinkElementGenerator _linkElementGenerator;
private MailLinkElementGenerator _mailLinkElementGenerator;
private void UpdateBuiltinElementGeneratorsFromOptions()
{
var options = Options;
// AddRemoveDefaultElementGeneratorOnDemand(ref newLineElementGenerator, options.ShowEndOfLine);
AddRemoveDefaultElementGeneratorOnDemand(ref _singleCharacterElementGenerator, options.ShowBoxForControlCharacters || options.ShowSpaces || options.ShowTabs);
AddRemoveDefaultElementGeneratorOnDemand(ref _linkElementGenerator, options.EnableHyperlinks);
AddRemoveDefaultElementGeneratorOnDemand(ref _mailLinkElementGenerator, options.EnableEmailHyperlinks);
}
private void AddRemoveDefaultElementGeneratorOnDemand<T>(ref T generator, bool demand)
where T : VisualLineElementGenerator, IBuiltinElementGenerator, new()
{
var hasGenerator = generator != null;
if (hasGenerator != demand)
{
if (demand)
{
generator = new T();
ElementGenerators.Add(generator);
}
else
{
ElementGenerators.Remove(generator);
generator = null;
}
}
generator?.FetchOptions(Options);
}
#endregion
#region Layers
internal readonly TextLayer TextLayer;
/// <summary>
/// Gets the list of layers displayed in the text view.
/// </summary>
public LayerCollection Layers { get; }
public sealed class LayerCollection : Collection<Control>
{
private readonly TextView _textView;
public LayerCollection(TextView textView)
{
_textView = textView;
}
protected override void ClearItems()
{
foreach (var control in Items)
{
_textView.VisualChildren.Remove(control);
}
base.ClearItems();
_textView.LayersChanged();
}
protected override void InsertItem(int index, Control item)
{
base.InsertItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
protected override void RemoveItem(int index)
{
base.RemoveItem(index);
_textView.VisualChildren.RemoveAt(index);
_textView.LayersChanged();
}
protected override void SetItem(int index, Control item)
{
_textView.VisualChildren.Remove(Items[index]);
base.SetItem(index, item);
_textView.VisualChildren.Add(item);
_textView.LayersChanged();
}
}
private void LayersChanged()
{
TextLayer.Index = Layers.IndexOf(TextLayer);
}
/// <summary>
/// Inserts a new layer at a position specified relative to an existing layer.
/// </summary>
/// <param name="layer">The new layer to insert.</param>
/// <param name="referencedLayer">The existing layer</param>
/// <param name="position">Specifies whether the layer is inserted above,below, or replaces the referenced layer</param>
public void InsertLayer(Control layer, KnownLayer referencedLayer, LayerInsertionPosition position)
{
if (layer == null)
throw new ArgumentNullException(nameof(layer));
if (!Enum.IsDefined(typeof(KnownLayer), referencedLayer))
throw new ArgumentOutOfRangeException(nameof(referencedLayer), (int)referencedLayer, nameof(KnownLayer));
if (!Enum.IsDefined(typeof(LayerInsertionPosition), position))
throw new ArgumentOutOfRangeException(nameof(position), (int)position, nameof(LayerInsertionPosition));
if (referencedLayer == KnownLayer.Background && position != LayerInsertionPosition.Above)
throw new InvalidOperationException("Cannot replace or insert below the background layer.");
var newPosition = new LayerPosition(referencedLayer, position);
LayerPosition.SetLayerPosition(layer, newPosition);
for (var i = 0; i < Layers.Count; i++)
{
var p = LayerPosition.GetLayerPosition(Layers[i]);
if (p != null)
{
if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Replace)
{
// found the referenced layer
switch (position)
{
case LayerInsertionPosition.Below:
Layers.Insert(i, layer);
return;
case LayerInsertionPosition.Above:
Layers.Insert(i + 1, layer);
return;
case LayerInsertionPosition.Replace:
Layers[i] = layer;
return;
}
}
else if (p.KnownLayer == referencedLayer && p.Position == LayerInsertionPosition.Above
|| p.KnownLayer > referencedLayer)
{
// we skipped the insertion position (referenced layer does not exist?)
Layers.Insert(i, layer);
return;
}
}
}
// inserting after all existing layers:
Layers.Add(layer);
}
#endregion
#region Inline object handling
private readonly List<InlineObjectRun> _inlineObjects = new List<InlineObjectRun>();
/// <summary>
/// Adds a new inline object.
/// </summary>
internal void AddInlineObject(InlineObjectRun inlineObject)
{
Debug.Assert(inlineObject.VisualLine != null);
// Remove inline object if its already added, can happen e.g. when recreating textrun for word-wrapping
var alreadyAdded = false;
for (var i = 0; i < _inlineObjects.Count; i++)
{
if (_inlineObjects[i].Element == inlineObject.Element)
{
RemoveInlineObjectRun(_inlineObjects[i], true);
_inlineObjects.RemoveAt(i);
alreadyAdded = true;
break;
}
}
_inlineObjects.Add(inlineObject);
if (!alreadyAdded)
{
VisualChildren.Add(inlineObject.Element);
((ISetLogicalParent)inlineObject.Element).SetParent(this);
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
}
private void MeasureInlineObjects()
{
// As part of MeasureOverride(), re-measure the inline objects
foreach (var inlineObject in _inlineObjects)
{
if (inlineObject.VisualLine.IsDisposed)
{
// Don't re-measure inline objects that are going to be removed anyways.
// If the inline object will be reused in a different VisualLine, we'll measure it in the AddInlineObject() call.
continue;
}
inlineObject.Element.Measure(new Size(double.PositiveInfinity, double.PositiveInfinity));
if (!inlineObject.Element.DesiredSize.IsClose(inlineObject.DesiredSize))
{
// the element changed size -> recreate its parent visual line
inlineObject.DesiredSize = inlineObject.Element.DesiredSize;
if (_allVisualLines.Remove(inlineObject.VisualLine))
{
DisposeVisualLine(inlineObject.VisualLine);
}
}
}
}
private readonly List<VisualLine> _visualLinesWithOutstandingInlineObjects = new List<VisualLine>();
private void RemoveInlineObjects(VisualLine visualLine)
{
// Delay removing inline objects:
// A document change immediately invalidates affected visual lines, but it does not
// cause an immediate redraw.
// To prevent inline objects from flickering when they are recreated, we delay removing
// inline objects until the next redraw.
if (visualLine.HasInlineObjects)
{
_visualLinesWithOutstandingInlineObjects.Add(visualLine);
}
}
/// <summary>
/// Remove the inline objects that were marked for removal.
/// </summary>
private void RemoveInlineObjectsNow()
{
if (_visualLinesWithOutstandingInlineObjects.Count == 0)
return;
_inlineObjects.RemoveAll(
ior =>
{
if (_visualLinesWithOutstandingInlineObjects.Contains(ior.VisualLine))
{
RemoveInlineObjectRun(ior, false);
return true;
}
return false;
});
_visualLinesWithOutstandingInlineObjects.Clear();
}
// Remove InlineObjectRun.Element from TextLayer.
// Caller of RemoveInlineObjectRun will remove it from inlineObjects collection.
private void RemoveInlineObjectRun(InlineObjectRun ior, bool keepElement)
{
// TODO: Focus
//if (!keepElement && ior.Element.IsKeyboardFocusWithin)
//{
// // When the inline element that has the focus is removed, it will reset the
// // focus to the main window without raising appropriate LostKeyboardFocus events.
// // To work around this, we manually set focus to the next focusable parent.
// UIElement element = this;
// while (element != null && !element.Focusable)
// {
// element = VisualTreeHelper.GetParent(element) as UIElement;
// }
// if (element != null)
// Keyboard.Focus(element);
//}
ior.VisualLine = null;
if (!keepElement)
VisualChildren.Remove(ior.Element);
}
#endregion
#region Brushes
/// <summary>
/// NonPrintableCharacterBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> NonPrintableCharacterBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("NonPrintableCharacterBrush", new SolidColorBrush(Color.FromArgb(145, 128, 128, 128)));
/// <summary>
/// Gets/sets the Brush used for displaying non-printable characters.
/// </summary>
public IBrush NonPrintableCharacterBrush
{
get => GetValue(NonPrintableCharacterBrushProperty);
set => SetValue(NonPrintableCharacterBrushProperty, value);
}
/// <summary>
/// LinkTextForegroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextForegroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextForegroundBrush", Brushes.Blue);
/// <summary>
/// Gets/sets the Brush used for displaying link texts.
/// </summary>
public IBrush LinkTextForegroundBrush
{
get => GetValue(LinkTextForegroundBrushProperty);
set => SetValue(LinkTextForegroundBrushProperty, value);
}
/// <summary>
/// LinkTextBackgroundBrush dependency property.
/// </summary>
public static readonly StyledProperty<IBrush> LinkTextBackgroundBrushProperty =
AvaloniaProperty.Register<TextView, IBrush>("LinkTextBackgroundBrush", Brushes.Transparent);
/// <summary>
/// Gets/sets the Brush used for the background of link texts.
/// </summary>
public IBrush LinkTextBackgroundBrush
{
get => GetValue(LinkTextBackgroundBrushProperty);
set => SetValue(LinkTextBackgroundBrushProperty, value);
}
#endregion
/// <summary>
/// LinkTextUnderlinedBrush dependency property.
/// </summary>
public static readonly StyledProperty<bool> LinkTextUnderlineProperty =
AvaloniaProperty.Register<TextView, bool>(nameof(LinkTextUnderline), true);
/// <summary>
/// Gets/sets whether to underline link texts.
/// </summary>
/// <remarks>
/// Note that when setting this property to false, link text remains clickable and the LinkTextForegroundBrush (if any) is still applied.
/// Set TextEditorOptions.EnableHyperlinks and EnableEmailHyperlinks to false to disable links completely.
/// </remarks>
public bool LinkTextUnderline
{
get => GetValue(LinkTextUnderlineProperty);
set => SetValue(LinkTextUnderlineProperty, value);
}
#region Redraw methods / VisualLine invalidation
/// <summary>
/// Causes the text editor to regenerate all visual lines.
/// </summary>
public void Redraw()
{
VerifyAccess();
ClearVisualLines();
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to regenerate the specified visual line.
/// </summary>
public void Redraw(VisualLine visualLine)
{
VerifyAccess();
if (_allVisualLines.Remove(visualLine))
{
DisposeVisualLine(visualLine);
InvalidateMeasure();
}
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// </summary>
public void Redraw(int offset, int length)
{
VerifyAccess();
var changedSomethingBeforeOrInLine = false;
for (var i = 0; i < _allVisualLines.Count; i++)
{
var visualLine = _allVisualLines[i];
var lineStart = visualLine.FirstDocumentLine.Offset;
var lineEnd = visualLine.LastDocumentLine.Offset + visualLine.LastDocumentLine.TotalLength;
if (offset <= lineEnd)
{
changedSomethingBeforeOrInLine = true;
if (offset + length >= lineStart)
{
_allVisualLines.RemoveAt(i--);
DisposeVisualLine(visualLine);
}
}
}
if (changedSomethingBeforeOrInLine)
{
// Repaint not only when something in visible area was changed, but also when anything in front of it
// was changed. We might have to redraw the line number margin. Or the highlighting changed.
// However, we'll try to reuse the existing VisualLines.
InvalidateMeasure();
}
}
/// <summary>
/// Causes a known layer to redraw.
/// This method does not invalidate visual lines;
/// use the <see cref="Redraw()"/> method to do that.
/// </summary>
[SuppressMessage("Microsoft.Usage", "CA1801:ReviewUnusedParameters", MessageId = "knownLayer",
Justification = "This method is meant to invalidate only a specific layer - I just haven't figured out how to do that, yet.")]
public void InvalidateLayer(KnownLayer knownLayer)
{
InvalidateMeasure();
}
/// <summary>
/// Causes the text editor to redraw all lines overlapping with the specified segment.
/// Does nothing if segment is null.
/// </summary>
public void Redraw(ISegment segment)
{
if (segment != null)
{
Redraw(segment.Offset, segment.Length);
}
}
/// <summary>
/// Invalidates all visual lines.
/// The caller of ClearVisualLines() must also call InvalidateMeasure() to ensure
/// that the visual lines will be recreated.
/// </summary>
private void ClearVisualLines()
{
if (_allVisualLines.Count != 0)
{
foreach (var visualLine in _allVisualLines)
{
DisposeVisualLine(visualLine);
}
_allVisualLines.Clear();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
}
}
private void DisposeVisualLine(VisualLine visualLine)
{
if (_newVisualLines != null && _newVisualLines.Contains(visualLine))
{
throw new ArgumentException("Cannot dispose visual line because it is in construction!");
}
visualLine.Dispose();
RemoveInlineObjects(visualLine);
}
#endregion
#region Get(OrConstruct)VisualLine
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// Returns null if the document line is outside the visible range.
/// </summary>
public VisualLine GetVisualLine(int documentLineNumber)
{
// TODO: EnsureVisualLines() ?
foreach (var visualLine in _allVisualLines)
{
Debug.Assert(visualLine.IsDisposed == false);
var start = visualLine.FirstDocumentLine.LineNumber;
var end = visualLine.LastDocumentLine.LineNumber;
if (documentLineNumber >= start && documentLineNumber <= end)
return visualLine;
}
return null;
}
/// <summary>
/// Gets the visual line that contains the document line with the specified number.
/// If that line is outside the visible range, a new VisualLine for that document line is constructed.
/// </summary>
public VisualLine GetOrConstructVisualLine(DocumentLine documentLine)
{
if (documentLine == null)
throw new ArgumentNullException("documentLine");
if (!this.Document.Lines.Contains(documentLine))
throw new InvalidOperationException("Line belongs to wrong document");
VerifyAccess();
VisualLine l = GetVisualLine(documentLine.LineNumber);
if (l == null)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
while (_heightTree.GetIsCollapsed(documentLine.LineNumber))
{
documentLine = documentLine.PreviousLine;
}
l = BuildVisualLine(documentLine,
globalTextRunProperties, paragraphProperties,
_elementGenerators.ToArray(), _lineTransformers.ToArray(),
_lastAvailableSize);
_allVisualLines.Add(l);
// update all visual top values (building the line might have changed visual top of other lines due to word wrapping)
foreach (var line in _allVisualLines)
{
line.VisualTop = _heightTree.GetVisualPosition(line.FirstDocumentLine);
}
}
return l;
}
#endregion
#region Visual Lines (fields and properties)
private List<VisualLine> _allVisualLines = new List<VisualLine>();
private ReadOnlyCollection<VisualLine> _visibleVisualLines;
private double _clippedPixelsOnTop;
private List<VisualLine> _newVisualLines;
/// <summary>
/// Gets the currently visible visual lines.
/// </summary>
/// <exception cref="VisualLinesInvalidException">
/// Gets thrown if there are invalid visual lines when this property is accessed.
/// You can use the <see cref="VisualLinesValid"/> property to check for this case,
/// or use the <see cref="EnsureVisualLines()"/> method to force creating the visual lines
/// when they are invalid.
/// </exception>
[SuppressMessage("Microsoft.Design", "CA1065:DoNotRaiseExceptionsInUnexpectedLocations")]
public ReadOnlyCollection<VisualLine> VisualLines
{
get
{
if (_visibleVisualLines == null)
throw new VisualLinesInvalidException();
return _visibleVisualLines;
}
}
/// <summary>
/// Gets whether the visual lines are valid.
/// Will return false after a call to Redraw().
/// Accessing the visual lines property will cause a <see cref="VisualLinesInvalidException"/>
/// if this property is <c>false</c>.
/// </summary>
public bool VisualLinesValid => _visibleVisualLines != null;
/// <summary>
/// Occurs when the TextView is about to be measured and will regenerate its visual lines.
/// This event may be used to mark visual lines as invalid that would otherwise be reused.
/// </summary>
public event EventHandler<VisualLineConstructionStartEventArgs> VisualLineConstructionStarting;
/// <summary>
/// Occurs when the TextView was measured and changed its visual lines.
/// </summary>
public event EventHandler VisualLinesChanged;
/// <summary>
/// If the visual lines are invalid, creates new visual lines for the visible part
/// of the document.
/// If all visual lines are valid, this method does nothing.
/// </summary>
/// <exception cref="InvalidOperationException">The visual line build process is already running.
/// It is not allowed to call this method during the construction of a visual line.</exception>
public void EnsureVisualLines()
{
Dispatcher.UIThread.VerifyAccess();
if (_inMeasure)
throw new InvalidOperationException("The visual line build process is already running! Cannot EnsureVisualLines() during Measure!");
if (!VisualLinesValid)
{
// increase priority for re-measure
InvalidateMeasure();
// force immediate re-measure
InvalidateVisual();
}
// Sometimes we still have invalid lines after UpdateLayout - work around the problem
// by calling MeasureOverride directly.
if (!VisualLinesValid)
{
Debug.WriteLine("UpdateLayout() failed in EnsureVisualLines");
MeasureOverride(_lastAvailableSize);
}
if (!VisualLinesValid)
throw new VisualLinesInvalidException("Internal error: visual lines invalid after EnsureVisualLines call");
}
#endregion
#region Measure
/// <summary>
/// Additonal amount that allows horizontal scrolling past the end of the longest line.
/// This is necessary to ensure the caret always is visible, even when it is at the end of the longest line.
/// </summary>
private const double AdditionalHorizontalScrollAmount = 3;
private Size _lastAvailableSize;
private bool _inMeasure;
/// <inheritdoc/>
protected override Size MeasureOverride(Size availableSize)
{
// We don't support infinite available width, so we'll limit it to 32000 pixels.
if (availableSize.Width > 32000)
availableSize = availableSize.WithWidth(32000);
if (!_canHorizontallyScroll && !availableSize.Width.IsClose(_lastAvailableSize.Width))
{
ClearVisualLines();
}
_lastAvailableSize = availableSize;
foreach (var layer in Layers)
{
layer.Measure(availableSize);
}
InvalidateVisual(); // = InvalidateArrange+InvalidateRender
MeasureInlineObjects();
double maxWidth;
if (_document == null)
{
// no document -> create empty list of lines
_allVisualLines = new List<VisualLine>();
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_allVisualLines.ToArray());
maxWidth = 0;
}
else
{
_inMeasure = true;
try
{
maxWidth = CreateAndMeasureVisualLines(availableSize);
}
finally
{
_inMeasure = false;
}
}
// remove inline objects only at the end, so that inline objects that were re-used are not removed from the editor
RemoveInlineObjectsNow();
maxWidth += AdditionalHorizontalScrollAmount;
var heightTreeHeight = DocumentHeight;
var options = Options;
double desiredHeight = Math.Min(availableSize.Height, heightTreeHeight);
double extraHeightToAllowScrollBelowDocument = 0;
if (options.AllowScrollBelowDocument)
{
if (!double.IsInfinity(_scrollViewport.Height))
{
// HACK: we need to keep at least Caret.MinimumDistanceToViewBorder visible so that we don't scroll back up when the user types after
// scrolling to the very bottom.
var minVisibleDocumentHeight = DefaultLineHeight;
// increase the extend height to allow scrolling below the document
extraHeightToAllowScrollBelowDocument = desiredHeight - minVisibleDocumentHeight;
}
}
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight + extraHeightToAllowScrollBelowDocument),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
return new Size(Math.Min(availableSize.Width, maxWidth), desiredHeight);
}
/// <summary>
/// Build all VisualLines in the visible range.
/// </summary>
/// <returns>Width the longest line</returns>
private double CreateAndMeasureVisualLines(Size availableSize)
{
TextRunProperties globalTextRunProperties = CreateGlobalTextRunProperties();
VisualLineTextParagraphProperties paragraphProperties = CreateParagraphProperties(globalTextRunProperties);
//Debug.WriteLine("Measure availableSize=" + availableSize + ", scrollOffset=" + _scrollOffset);
var firstLineInView = _heightTree.GetLineByVisualPosition(_scrollOffset.Y);
// number of pixels clipped from the first visual line(s)
_clippedPixelsOnTop = _scrollOffset.Y - _heightTree.GetVisualPosition(firstLineInView);
// clippedPixelsOnTop should be >= 0, except for floating point inaccurracy.
Debug.Assert(_clippedPixelsOnTop >= -ExtensionMethods.Epsilon);
_newVisualLines = new List<VisualLine>();
TextLayer.SetVisualLines(_visibleVisualLines);
SetScrollData(availableSize,
new Size(maxWidth, heightTreeHeight),
_scrollOffset);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
{
var visualLine = GetVisualLine(nextLine.LineNumber) ??
BuildVisualLine(nextLine,
globalTextRunProperties, paragraphProperties,
elementGeneratorsArray, lineTransformersArray,
availableSize);
visualLine.VisualTop = _scrollOffset.Y + yPos;
nextLine = visualLine.LastDocumentLine.NextLine;
yPos += visualLine.Height;
foreach (var textLine in visualLine.TextLines)
{
if (textLine.WidthIncludingTrailingWhitespace > maxWidth)
maxWidth = textLine.WidthIncludingTrailingWhitespace;
}
_newVisualLines.Add(visualLine);
}
foreach (var line in _allVisualLines)
{
Debug.Assert(line.IsDisposed == false);
if (!_newVisualLines.Contains(line))
DisposeVisualLine(line);
}
_allVisualLines = _newVisualLines;
// visibleVisualLines = readonly copy of visual lines
_visibleVisualLines = new ReadOnlyCollection<VisualLine>(_newVisualLines.ToArray());
_newVisualLines = null;
if (_allVisualLines.Any(line => line.IsDisposed))
{
throw new InvalidOperationException("A visual line was disposed even though it is still in use.\n" +
"This can happen when Redraw() is called during measure for lines " +
"that are already constructed.");
}
return maxWidth;
}
#endregion
#region BuildVisualLine
private TextFormatter _formatter;
internal TextViewCachedElements CachedElements;
private TextRunProperties CreateGlobalTextRunProperties()
{
var p = new GlobalTextRunProperties();
p.typeface = this.CreateTypeface();
p.fontRenderingEmSize = FontSize;
p.foregroundBrush = GetValue(TextElement.ForegroundProperty);
ExtensionMethods.CheckIsFrozen(p.foregroundBrush);
p.cultureInfo = CultureInfo.CurrentCulture;
return p;
}
private VisualLineTextParagraphProperties CreateParagraphProperties(TextRunProperties defaultTextRunProperties)
{
return new VisualLineTextParagraphProperties
{
defaultTextRunProperties = defaultTextRunProperties,
textWrapping = _canHorizontallyScroll ? TextWrapping.NoWrap : TextWrapping.Wrap,
tabSize = Options.IndentationSize * WideSpaceWidth
};
}
private VisualLine BuildVisualLine(DocumentLine documentLine,
TextRunProperties globalTextRunProperties,
VisualLineTextParagraphProperties paragraphProperties,
IReadOnlyList<VisualLineElementGenerator> elementGeneratorsArray,
IReadOnlyList<IVisualLineTransformer> lineTransformersArray,
Size availableSize)
{
if (_heightTree.GetIsCollapsed(documentLine.LineNumber))
throw new InvalidOperationException("Trying to build visual line from collapsed line");
//Debug.WriteLine("Building line " + documentLine.LineNumber);
VisualLine visualLine = new VisualLine(this, documentLine);
VisualLineTextSource textSource = new VisualLineTextSource(visualLine)
{
Document = _document,
GlobalTextRunProperties = globalTextRunProperties,
TextView = this
};
visualLine.ConstructVisualElements(textSource, elementGeneratorsArray);
if (visualLine.FirstDocumentLine != visualLine.LastDocumentLine)
{
// Check whether the lines are collapsed correctly:
double firstLinePos = _heightTree.GetVisualPosition(visualLine.FirstDocumentLine.NextLine);
double lastLinePos = _heightTree.GetVisualPosition(visualLine.LastDocumentLine.NextLine ?? visualLine.LastDocumentLine);
if (!firstLinePos.IsClose(lastLinePos))
{
for (int i = visualLine.FirstDocumentLine.LineNumber + 1; i <= visualLine.LastDocumentLine.LineNumber; i++)
{
if (!_heightTree.GetIsCollapsed(i))
throw new InvalidOperationException("Line " + i + " was skipped by a VisualLineElementGenerator, but it is not collapsed.");
}
throw new InvalidOperationException("All lines collapsed but visual pos different - height tree inconsistency?");
}
}
visualLine.RunTransformers(textSource, lineTransformersArray);
// now construct textLines:
TextLineBreak lastLineBreak = null;
var textOffset = 0;
var textLines = new List<TextLine>();
while (textOffset <= visualLine.VisualLengthWithEndOfLineMarker)
{
var textLine = _formatter.FormatLine(
textSource,
textOffset,
availableSize.Width,
paragraphProperties,
lastLineBreak
);
textLines.Add(textLine);
textOffset += textLine.Length;
// exit loop so that we don't do the indentation calculation if there's only a single line
if (textOffset >= visualLine.VisualLengthWithEndOfLineMarker)
break;
if (paragraphProperties.firstLineInParagraph)
{
paragraphProperties.firstLineInParagraph = false;
TextEditorOptions options = this.Options;
double indentation = 0;
if (options.InheritWordWrapIndentation)
{
// determine indentation for next line:
int indentVisualColumn = GetIndentationVisualColumn(visualLine);
if (indentVisualColumn > 0 && indentVisualColumn < textOffset)
{
indentation = textLine.GetDistanceFromCharacterHit(new CharacterHit(indentVisualColumn, 0));
}
}
indentation += options.WordWrapIndentation;
// apply the calculated indentation unless it's more than half of the text editor size:
if (indentation > 0 && indentation * 2 < availableSize.Width)
paragraphProperties.indent = indentation;
}
lastLineBreak = textLine.TextLineBreak;
}
visualLine.SetTextLines(textLines);
_heightTree.SetHeight(visualLine.FirstDocumentLine, visualLine.Height);
return visualLine;
}
private static int GetIndentationVisualColumn(VisualLine visualLine)
{
if (visualLine.Elements.Count == 0)
return 0;
var column = 0;
var elementIndex = 0;
var element = visualLine.Elements[elementIndex];
while (element.IsWhitespace(column))
{
column++;
if (column == element.VisualColumn + element.VisualLength)
{
elementIndex++;
if (elementIndex == visualLine.Elements.Count)
break;
element = visualLine.Elements[elementIndex];
}
}
return column;
}
#endregion
#region Arrange
/// <summary>
/// Arrange implementation.
/// </summary>
protected override Size ArrangeOverride(Size finalSize)
{
EnsureVisualLines();
foreach (var layer in Layers)
{
layer.Arrange(new Rect(new Point(0, 0), finalSize));
}
if (_document == null || _allVisualLines.Count == 0)
return finalSize;
// validate scroll position
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (_scrollOffset.X + finalSize.Width > _scrollExtent.Width)
{
newScrollOffsetX = Math.Max(0, _scrollExtent.Width - finalSize.Width);
}
if (_scrollOffset.Y + finalSize.Height > _scrollExtent.Height)
{
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
// Apply final view port and offset
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
InvalidateMeasure();
if (_visibleVisualLines != null)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visualLine in _visibleVisualLines)
{
var offset = 0;
foreach (var textLine in visualLine.TextLines)
{
foreach (var span in textLine.TextRuns)
{
var inline = span as InlineObjectRun;
if (inline?.VisualLine != null)
{
Debug.Assert(_inlineObjects.Contains(inline));
var distance = textLine.GetDistanceFromCharacterHit(new CharacterHit(offset));
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
{
InvalidateMeasure(DispatcherPriority.Normal);
}
if (_visibleVisualLines != null)
{
}
}
}
InvalidateCursorIfPointerWithinTextView();
return finalSize;
}
#endregion
#region Render
private readonly ObserveAddRemoveCollection<IBackgroundRenderer> _backgroundRenderers;
/// <summary>
/// Gets the list of background renderers.
/// </summary>
public IList<IBackgroundRenderer> BackgroundRenderers => _backgroundRenderers;
private void BackgroundRenderer_Added(IBackgroundRenderer renderer)
{
ConnectToTextView(renderer);
InvalidateLayer(renderer.Layer);
}
private void BackgroundRenderer_Removed(IBackgroundRenderer renderer)
{
DisconnectFromTextView(renderer);
InvalidateLayer(renderer.Layer);
}
/// <inheritdoc/>
public override void Render(DrawingContext drawingContext)
{
if (!VisualLinesValid)
{
return;
}
RenderBackground(drawingContext, KnownLayer.Background);
foreach (var line in _visibleVisualLines)
{
IBrush currentBrush = null;
var startVc = 0;
var length = 0;
foreach (var element in line.Elements)
{
if (currentBrush == null || !currentBrush.Equals(element.BackgroundBrush))
{
if (currentBrush != null)
{
var builder =
new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
startVc = element.VisualColumn;
length = element.DocumentLength;
currentBrush = element.BackgroundBrush;
}
else
{
length += element.VisualLength;
}
}
if (currentBrush != null)
{
var builder = new BackgroundGeometryBuilder
{
AlignToWholePixels = true,
CornerRadius = 3
};
foreach (var rect in BackgroundGeometryBuilder.GetRectsFromVisualSegment(this, line, startVc, startVc + length))
builder.AddRectangle(this, rect);
var geometry = builder.CreateGeometry();
if (geometry != null)
{
drawingContext.DrawGeometry(currentBrush, null, geometry);
}
}
}
}
internal void RenderBackground(DrawingContext drawingContext, KnownLayer layer)
{
// this is necessary so hit-testing works properly and events get tunneled to the TextView.
drawingContext.FillRectangle(Brushes.Transparent, Bounds);
foreach (var bg in _backgroundRenderers)
{
if (bg.Layer == layer)
{
bg.Draw(this, drawingContext);
}
}
}
internal void ArrangeTextLayer(IList<VisualLineDrawingVisual> visuals)
{
var pos = new Point(-_scrollOffset.X, -_clippedPixelsOnTop);
foreach (var visual in visuals)
{
var t = visual.RenderTransform as TranslateTransform;
if (t == null || t.X != pos.X || t.Y != pos.Y)
{
visual.RenderTransform = new TranslateTransform(pos.X, pos.Y);
}
pos = new Point(pos.X, pos.Y + visual.LineHeight);
}
}
#endregion
#region IScrollInfo implementation
/// <summary>
/// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
private Vector _scrollOffset;
/// <summary>
/// Size of the viewport.
/// </summary>
private Size _scrollViewport;
private void ClearScrollData()
#region IScrollInfo implementation
/// <summary>
/// Size of the document, in pixels.
/// </summary>
private Size _scrollExtent;
/// <summary>
/// Offset of the scroll position.
/// </summary>
}
return false;
}
private void OnScrollChange()
{
((ILogicalScrollable)this).RaiseScrollInvalidated(EventArgs.Empty);
}
private bool _canVerticallyScroll = true;
private bool _canHorizontallyScroll = true;
/// <summary>
/// Gets the horizontal scroll offset.
/// </summary>
public double HorizontalOffset => _scrollOffset.X;
/// <summary>
/// Gets the vertical scroll offset.
/// </summary>
public double VerticalOffset => _scrollOffset.Y;
/// <summary>
/// Gets the scroll offset;
/// </summary>
public Vector ScrollOffset => _scrollOffset;
/// <summary>
/// Occurs when the scroll offset has changed.
/// </summary>
public event EventHandler ScrollOffsetChanged;
private void SetScrollOffset(Vector vector)
{
if (!_canHorizontallyScroll)
{
vector = new Vector(0, vector.Y);
}
if (!_canVerticallyScroll)
{
vector = new Vector(vector.X, 0);
}
if (!_scrollOffset.IsClose(vector))
{
_scrollOffset = vector;
ScrollOffsetChanged?.Invoke(this, EventArgs.Empty);
}
}
private bool _defaultTextMetricsValid;
private double _wideSpaceWidth; // Width of an 'x'. Used as basis for the tab width, and for scrolling.
private double _defaultLineHeight; // Height of a line containing 'x'. Used for scrolling.
private double _defaultBaseline; // Baseline of a line containing 'x'. Used for TextTop/TextBottom calculation.
/// <summary>
/// Gets the width of a 'wide space' (the space width used for calculating the tab size).
/// </summary>
/// <remarks>
/// This is the width of an 'x' in the current font.
/// We do not measure the width of an actual space as that would lead to tiny tabs in
/// some proportional fonts.
/// For monospaced fonts, this property will return the expected value, as 'x' and ' ' have the same width.
/// </remarks>
public double WideSpaceWidth
{
get
{
CalculateDefaultTextMetrics();
return _wideSpaceWidth;
}
}
/// <summary>
/// Gets the default line height. This is the height of an empty line or a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different line height.
/// </summary>
public double DefaultLineHeight
{
get
{
CalculateDefaultTextMetrics();
return _defaultLineHeight;
}
}
/// <summary>
/// Gets the default baseline position. This is the difference between <see cref="VisualYPosition.TextTop"/>
/// and <see cref="VisualYPosition.Baseline"/> for a line containing regular text.
/// Lines that include formatted text or custom UI elements may have a different baseline.
/// </summary>
public double DefaultBaseline
{
get
{
CalculateDefaultTextMetrics();
return _defaultBaseline;
}
}
private void InvalidateDefaultTextMetrics()
{
_defaultTextMetricsValid = false;
if (_heightTree != null)
{
// calculate immediately so that height tree gets updated
CalculateDefaultTextMetrics();
}
}
private void CalculateDefaultTextMetrics()
{
if (_defaultTextMetricsValid)
return;
_defaultTextMetricsValid = true;
if (_formatter != null)
{
var textRunProperties = CreateGlobalTextRunProperties();
var line = _formatter.FormatLine(
new SimpleTextSource("x", textRunProperties),
0, 32000,
new VisualLineTextParagraphProperties { defaultTextRunProperties = textRunProperties },
null);
_wideSpaceWidth = Math.Max(1, line.WidthIncludingTrailingWhitespace);
_defaultBaseline = Math.Max(1, line.Baseline);
_defaultLineHeight = Math.Max(1, line.Height);
}
else
{
_wideSpaceWidth = FontSize / 2;
_defaultBaseline = FontSize;
_defaultLineHeight = FontSize + 3;
}
// Update heightTree.DefaultLineHeight, if a document is loaded.
if (_heightTree != null)
_heightTree.DefaultLineHeight = _defaultLineHeight;
}
private static double ValidateVisualOffset(double offset)
{
if (double.IsNaN(offset))
throw new ArgumentException("offset must not be NaN");
if (offset < 0)
return 0;
return offset;
}
/// <summary>
/// Scrolls the text view so that the specified rectangle gets visible.
/// </summary>
public virtual void MakeVisible(Rect rectangle)
{
var visibleRectangle = new Rect(_scrollOffset.X, _scrollOffset.Y,
_scrollViewport.Width, _scrollViewport.Height);
var newScrollOffsetX = _scrollOffset.X;
var newScrollOffsetY = _scrollOffset.Y;
if (rectangle.X < visibleRectangle.X)
{
if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.X + rectangle.Width / 2;
}
else
{
newScrollOffsetX = rectangle.X;
}
}
else if (rectangle.Right > visibleRectangle.Right)
{
newScrollOffsetX = rectangle.Right - _scrollViewport.Width;
}
if (rectangle.Y < visibleRectangle.Y)
{
if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Y + rectangle.Height / 2;
}
else
{
newScrollOffsetY = rectangle.Y;
}
}
else if (rectangle.Bottom > visibleRectangle.Bottom)
{
newScrollOffsetY = rectangle.Bottom - _scrollViewport.Height;
}
newScrollOffsetX = ValidateVisualOffset(newScrollOffsetX);
newScrollOffsetY = ValidateVisualOffset(newScrollOffsetY);
var newScrollOffset = new Vector(newScrollOffsetX, newScrollOffsetY);
if (!_scrollOffset.IsClose(newScrollOffset))
{
SetScrollOffset(newScrollOffset);
OnScrollChange();
InvalidateMeasure();
}
}
#endregion
#region Visual element pointer handling
[ThreadStatic] private static bool _invalidCursor;
//private VisualLineElement _currentHoveredElement;
/// <summary>
/// Updates the pointe cursor, but with background priority.
/// </summary>
public static void InvalidateCursor()
{
if (!_invalidCursor)
{
_invalidCursor = true;
Dispatcher.UIThread.InvokeAsync(
delegate
{
_invalidCursor = false;
//MouseDevice.Instance.UpdateCursor();
},
DispatcherPriority.Background // fixes issue #288
);
}
}
internal void InvalidateCursorIfPointerWithinTextView()
{
// Don't unnecessarily call Mouse.UpdateCursor() if the mouse is outside the text view.
// Unnecessary updates may cause the mouse pointer to flicker
// (e.g. if it is over a window border, it blinks between Resize and Normal)
if (IsPointerOver)
{
InvalidateCursor();
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
base.OnPointerMoved(e);
//var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
//// Change back to default if hover on a different element
//if (_currentHoveredElement != element)
//{
// Cursor = Parent.Cursor; // uses TextArea's ContentPresenter cursor
// _currentHoveredElement = element;
//}
//element?.OnQueryCursor(e);
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
base.OnPointerPressed(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerPressed(e);
}
}
protected override void OnPointerReleased(PointerReleasedEventArgs e)
{
base.OnPointerReleased(e);
if (!e.Handled)
{
EnsureVisualLines();
var element = GetVisualLineElementFromPosition(e.GetPosition(this) + _scrollOffset);
element?.OnPointerReleased(e);
}
}
#endregion
#region Getting elements from Visual Position
/// <summary>
/// Gets the visual line at the specified document position (relative to start of document).
/// Returns null if there is no visual line for the position (e.g. the position is outside the visible
/// text area).
/// </summary>
public VisualLine GetVisualLineFromVisualTop(double visualTop)
{
// TODO: change this method to also work outside the visible range -
// required to make GetPosition work as expected!
EnsureVisualLines();
foreach (var vl in VisualLines)
{
if (visualTop < vl.VisualTop)
continue;
if (visualTop < vl.VisualTop + vl.Height)
return vl;
}
return null;
}
/// <summary>
/// Gets the visual top position (relative to start of document) from a document line number.
/// </summary>
public double GetVisualTopByDocumentLine(int line)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetVisualPosition(_heightTree.GetLineByNumber(line));
}
private VisualLineElement GetVisualLineElementFromPosition(Point visualPosition)
{
var vl = GetVisualLineFromVisualTop(visualPosition.Y);
if (vl != null)
{
var column = vl.GetVisualColumnFloor(visualPosition);
foreach (var element in vl.Elements)
{
if (element.VisualColumn + element.VisualLength <= column)
continue;
return element;
}
}
return null;
}
#endregion
#region Visual Position <-> TextViewPosition
/// <summary>
/// Gets the visual position from a text view position.
/// </summary>
/// <param name="position">The text view position.</param>
/// <param name="yPositionMode">The mode how to retrieve the Y position.</param>
/// <returns>The position in device-independent pixels relative
/// to the top left corner of the document.</returns>
public Point GetVisualPosition(TextViewPosition position, VisualYPosition yPositionMode)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var documentLine = Document.GetLineByNumber(position.Line);
var visualLine = GetOrConstructVisualLine(documentLine);
var visualColumn = position.VisualColumn;
if (visualColumn < 0)
{
var offset = documentLine.Offset + position.Column - 1;
visualColumn = visualLine.GetVisualColumn(offset - visualLine.FirstDocumentLine.Offset);
}
return visualLine.GetVisualPosition(visualColumn, position.IsAtEndOfLine, yPositionMode);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is within a character, it is rounded to the next character boundary.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPosition(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPosition(visualPosition, Options.EnableVirtualSpace);
}
/// <summary>
/// Gets the text view position from the specified visual position.
/// If the position is inside a character, the position in front of the character is returned.
/// </summary>
/// <param name="visualPosition">The position in device-independent pixels relative
/// to the top left corner of the document.</param>
/// <returns>The logical position, or null if the position is outside the document.</returns>
public TextViewPosition? GetPositionFloor(Point visualPosition)
{
VerifyAccess();
if (Document == null)
throw ThrowUtil.NoDocumentAssigned();
var line = GetVisualLineFromVisualTop(visualPosition.Y);
return line?.GetTextViewPositionFloor(visualPosition, Options.EnableVirtualSpace);
}
#endregion
#region Service Provider
/// <summary>
/// Gets a service container used to associate services with the text view.
/// </summary>
internal IServiceContainer Services { get; } = new ServiceContainer();
/// <summary>
/// Retrieves a service from the text view.
/// If the service is not found in the <see cref="Services"/> container,
/// this method will also look for it in the current document's service provider.
/// </summary>
public virtual object GetService(Type serviceType)
{
var instance = Services.GetService(serviceType);
if (instance == null && _document != null)
{
instance = _document.ServiceProvider.GetService(serviceType);
}
return instance;
}
private void ConnectToTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.AddToTextView(this);
}
private void DisconnectFromTextView(object obj)
{
var c = obj as ITextViewConnect;
c?.RemoveFromTextView(this);
}
#endregion
#region PointerHover
/// <summary>
/// The PreviewPointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHover), RoutingStrategies.Tunnel, typeof(TextView));
/// <summary>
/// The PointerHover event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHover), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// The PreviewPointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PreviewPointerHoverStopped), RoutingStrategies.Tunnel,
typeof(TextView));
/// <summary>
/// The PointerHoverStopped event.
/// </summary>
public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent =
RoutedEvent.Register<PointerEventArgs>(nameof(PointerHoverStopped), RoutingStrategies.Bubble,
typeof(TextView));
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHover
{
add => AddHandler(PreviewPointerHoverEvent, value);
remove => RemoveHandler(PreviewPointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointer has hovered over a fixed location for some time.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHover
{
add => AddHandler(PointerHoverEvent, value);
remove => RemoveHandler(PointerHoverEvent, value);
}
/// <summary>
/// Occurs when the pointe had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PreviewPointerHoverStopped
{
add => AddHandler(PreviewPointerHoverStoppedEvent, value);
remove => RemoveHandler(PreviewPointerHoverStoppedEvent, value);
}
/// <summary>
/// Occurs when the pointer had previously hovered but now started moving again.
/// </summary>
public event EventHandler<PointerEventArgs> PointerHoverStopped
{
add => AddHandler(PointerHoverStoppedEvent, value);
remove => RemoveHandler(PointerHoverStoppedEvent, value);
}
private readonly PointerHoverLogic _hoverLogic;
private void RaiseHoverEventPair(PointerEventArgs e, RoutedEvent tunnelingEvent, RoutedEvent bubblingEvent)
{
e.RoutedEvent = tunnelingEvent;
RaiseEvent(e);
e.RoutedEvent = bubblingEvent;
RaiseEvent(e);
}
#endregion
/// <summary>
/// Collapses lines for the purpose of scrolling. <see cref="DocumentLine"/>s marked as collapsed will be hidden
/// and not used to start the generation of a <see cref="VisualLine"/>.
/// </summary>
/// <remarks>
/// This method is meant for <see cref="VisualLineElementGenerator"/>s that cause <see cref="VisualLine"/>s to span
/// multiple <see cref="DocumentLine"/>s. Do not call it without providing a corresponding
/// <see cref="VisualLineElementGenerator"/>.
/// If you want to create collapsible text sections, see <see cref="Folding.FoldingManager"/>.
///
/// Note that if you want a VisualLineElement to span from line N to line M, then you need to collapse only the lines
/// N+1 to M. Do not collapse line N itself.
///
/// When you no longer need the section to be collapsed, call <see cref="CollapsedLineSection.Uncollapse()"/> on the
/// <see cref="CollapsedLineSection"/> returned from this method.
/// </remarks>
public CollapsedLineSection CollapseLines(DocumentLine start, DocumentLine end)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.CollapseText(start, end);
}
/// <summary>
/// Gets the height of the document.
/// </summary>
public double DocumentHeight => _heightTree?.TotalHeight ?? 0;
/// <summary>
/// Gets the document line at the specified visual position.
/// </summary>
public DocumentLine GetDocumentLineByVisualTop(double visualTop)
{
VerifyAccess();
if (_heightTree == null)
throw ThrowUtil.NoDocumentAssigned();
return _heightTree.GetLineByVisualPosition(visualTop);
}
/// <inheritdoc/>
protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change)
{
base.OnPropertyChanged(change);
if (change.Property == TemplatedControl.ForegroundProperty
|| change.Property == NonPrintableCharacterBrushProperty
|| change.Property == LinkTextBackgroundBrushProperty
|| change.Property == LinkTextForegroundBrushProperty
|| change.Property == LinkTextUnderlineProperty)
{
// changing brushes requires recreating the cached elements
RecreateCachedElements();
Redraw();
}
if (change.Property == TemplatedControl.FontFamilyProperty
|| change.Property == TemplatedControl.FontSizeProperty
|| change.Property == TemplatedControl.FontStyleProperty
|| change.Property == TemplatedControl.FontWeightProperty)
{
// changing font properties requires recreating cached elements
RecreateCachedElements();
// and we need to re-measure the font metrics:
InvalidateDefaultTextMetrics();
Redraw();
}
if (change.Property == ColumnRulerPenProperty)
{
_columnRulerRenderer.SetRuler(Options.ColumnRulerPositions, ColumnRulerPen);
}
if (change.Property == CurrentLineBorderProperty)
{
_currentLineHighlighRenderer.BorderPen = CurrentLineBorder;
}
if (change.Property == CurrentLineBackgroundProperty)
{
_currentLineHighlighRenderer.BackgroundBrush = CurrentLineBackground;
}
}
/// <summary>
/// The pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public static readonly StyledProperty<IPen> ColumnRulerPenProperty =
AvaloniaProperty.Register<TextView, IPen>("ColumnRulerBrush", CreateFrozenPen(new SolidColorBrush(Color.FromArgb(90, 128, 128, 128))));
private static ImmutablePen CreateFrozenPen(IBrush brush)
{
var pen = new ImmutablePen(brush?.ToImmutable());
return pen;
}
bool ILogicalScrollable.BringIntoView(IControl target, Rect rectangle)
{
if (rectangle.IsEmpty || target == null || target == this || !this.IsVisualAncestorOf(target))
{
return false;
}
// TODO:
// Convert rectangle into our coordinate space.
//var childTransform = target.TransformToVisual(this);
//rectangle = childTransform.Value(rectangle);
MakeVisible(rectangle.WithX(rectangle.X + _scrollOffset.X).WithY(rectangle.Y + _scrollOffset.Y));
return true;
}
IControl ILogicalScrollable.GetControlInDirection(NavigationDirection direction, IControl from)
{
return null;
}
event EventHandler ILogicalScrollable.ScrollInvalidated
{
add => _scrollInvalidated += value;
remove => _scrollInvalidated -= value;
}
void ILogicalScrollable.RaiseScrollInvalidated(EventArgs e)
{
_scrollInvalidated?.Invoke(this, e);
}
/// <summary>
/// Gets/Sets the pen used to draw the column ruler.
/// <seealso cref="TextEditorOptions.ShowColumnRulers"/>
/// </summary>
public IPen ColumnRulerPen
{
get => GetValue(ColumnRulerPenProperty);
set => SetValue(ColumnRulerPenProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBackground"/> property.
/// </summary>
public static readonly StyledProperty<IBrush> CurrentLineBackgroundProperty =
AvaloniaProperty.Register<TextView, IBrush>("CurrentLineBackground");
/// <summary>
/// Gets/Sets the background brush used by current line highlighter.
/// </summary>
public IBrush CurrentLineBackground
{
get => GetValue(CurrentLineBackgroundProperty);
set => SetValue(CurrentLineBackgroundProperty, value);
}
/// <summary>
/// The <see cref="CurrentLineBorder"/> property.
/// </summary>
public static readonly StyledProperty<IPen> CurrentLineBorderProperty =
AvaloniaProperty.Register<TextView, IPen>("CurrentLineBorder");
/// <summary>
/// Gets/Sets the background brush used for the current line.
/// </summary>
public IPen CurrentLineBorder
{
get => GetValue(CurrentLineBorderProperty);
set => SetValue(CurrentLineBorderProperty, value);
}
/// <summary>
/// Gets/Sets highlighted line number.
/// </summary>
public int HighlightedLine
{
get => _currentLineHighlighRenderer.Line;
set => _currentLineHighlighRenderer.Line = value;
}
/// <summary>
/// Empty line selection width.
/// </summary>
public virtual double EmptyLineSelectionWidth => 1;
bool ILogicalScrollable.CanHorizontallyScroll
{
get => _canHorizontallyScroll;
set
{
if (_canHorizontallyScroll != value)
{
_canHorizontallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.CanVerticallyScroll
{
get => _canVerticallyScroll;
set
{
if (_canVerticallyScroll != value)
{
_canVerticallyScroll = value;
ClearVisualLines();
InvalidateMeasure();
}
}
}
bool ILogicalScrollable.IsLogicalScrollEnabled => true;
Size ILogicalScrollable.ScrollSize => new Size(10, 50);
Size ILogicalScrollable.PageScrollSize => new Size(10, 100);
Size IScrollable.Extent => _scrollExtent;
Vector IScrollable.Offset
{
get => _scrollOffset;
set
{
value = new Vector(ValidateVisualOffset(value.X), ValidateVisualOffset(value.Y));
var isX = !_scrollOffset.X.IsClose(value.X);
var isY = !_scrollOffset.Y.IsClose(value.Y);
if (isX || isY)
{
SetScrollOffset(value);
if (isX)
{
InvalidateVisual();
TextLayer.InvalidateVisual();
}
InvalidateMeasure();
}
}
}
Size IScrollable.Viewport => _scrollViewport;
}
}
<MSG> Fix scroll issue
<DFF> @@ -967,9 +967,8 @@ namespace AvaloniaEdit.Rendering
TextLayer.SetVisualLines(_visibleVisualLines);
- SetScrollData(availableSize,
- new Size(maxWidth, heightTreeHeight),
- _scrollOffset);
+ // Size of control (scorll viewport) might be changed during ArrageOverride. We only need document size for now.
+ _documentSize = new Size(maxWidth, heightTreeHeight);
VisualLinesChanged?.Invoke(this, EventArgs.Empty);
@@ -1208,10 +1207,8 @@ namespace AvaloniaEdit.Rendering
newScrollOffsetY = Math.Max(0, _scrollExtent.Height - finalSize.Height);
}
- if (SetScrollData(_scrollViewport, _scrollExtent, new Vector(newScrollOffsetX, newScrollOffsetY)))
- {
- InvalidateMeasure(DispatcherPriority.Normal);
- }
+ // Apply final view port and offset
+ SetScrollData(finalSize, _documentSize, new Vector(newScrollOffsetX, newScrollOffsetY));
if (_visibleVisualLines != null)
{
@@ -1355,10 +1352,15 @@ namespace AvaloniaEdit.Rendering
#region IScrollInfo implementation
/// <summary>
- /// Size of the document, in pixels.
+ /// Size of the scroll, in pixels.
/// </summary>
private Size _scrollExtent;
+ /// <summary>
+ /// Size of the document, in pixels.
+ /// </summary>
+ private Size _documentSize;
+
/// <summary>
/// Offset of the scroll position.
/// </summary>
| 10 | Fix scroll issue | 8 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067899 | <NME> AccessTokenController.php
<BEF> <?php
namespace Dusterio\LumenPassport\Http\Controllers;
use Laravel\Passport\Passport;
use Laravel\Passport\Token;
use Laminas\Diactoros\Response as Psr7Response;
use Psr\Http\Message\ServerRequestInterface;
use Dusterio\LumenPassport\LumenPassport;
/**
* Class AccessTokenController
* @package Dusterio\LumenPassport\Http\Controllers
*/
class AccessTokenController extends \Laravel\Passport\Http\Controllers\AccessTokenController
{
/**
* Authorize a client to access the user's account.
*
* @param ServerRequestInterface $request
* @return Response
*/
public function issueToken(ServerRequestInterface $request)
{
$response = $this->withErrorHandling(function () use ($request) {
$input = (array) $request->getParsedBody();
$clientId = isset($input['client_id']) ? $input['client_id'] : null;
// Overwrite password grant at the last minute to add support for customized TTLs
$this->server->enableGrantType(
$this->makePasswordGrant(), LumenPassport::tokensExpireIn(null, $clientId)
);
return $this->server->respondToAccessTokenRequest($request, new Psr7Response);
});
if ($response->getStatusCode() < 200 || $response->getStatusCode() > 299) {
return $response;
}
$payload = json_decode($response->getBody()->__toString(), true);
if (isset($payload['access_token'])) {
$tokenId = $this->jwt->parse($payload['access_token'])->getClaim('jti');
$token = $this->tokens->find($tokenId);
if ($token->client->firstParty() && LumenPassport::$allowMultipleTokens) {
// We keep previous tokens for password clients
} else {
$this->revokeOrDeleteAccessTokens($token, $tokenId);
}
}
return $response;
}
/**
* Create and configure a Password grant instance.
*
* @return \League\OAuth2\Server\Grant\PasswordGrant
*/
private function makePasswordGrant()
{
$grant = new \League\OAuth2\Server\Grant\PasswordGrant(
app()->make(\Laravel\Passport\Bridge\UserRepository::class),
app()->make(\Laravel\Passport\Bridge\RefreshTokenRepository::class)
);
$grant->setRefreshTokenTTL(Passport::refreshTokensExpireIn());
return $grant;
}
/**
* Revoke the user's other access tokens for the client.
*
* @param Token $token
* @param string $tokenId
* @return void
*/
protected function revokeOrDeleteAccessTokens(Token $token, $tokenId)
{
$query = Token::where('user_id', $token->user_id)->where('client_id', $token->client_id);
if ($tokenId) {
$query->where('id', '<>', $tokenId);
}
$query->update(['revoked' => true]);
}
}
<MSG> Add compatibility for `lcobucci/jwt` `^4.0`
<DFF> @@ -41,8 +41,20 @@ class AccessTokenController extends \Laravel\Passport\Http\Controllers\AccessTok
$payload = json_decode($response->getBody()->__toString(), true);
if (isset($payload['access_token'])) {
- $tokenId = $this->jwt->parse($payload['access_token'])->getClaim('jti');
+ /* @deprecated the jwt property will be removed in a future Laravel Passport release */
+ $token = $this->jwt->parse($payload['access_token']);
+ if (method_exists($token, 'getClaim')) {
+ $tokenId = $token->getClaim('jti');
+ } else if (method_exists($token, 'claims')) {
+ $tokenId = $token->claims()->get('jti');
+ } else {
+ throw new \RuntimeException('This package is not compatible to the used Laravel Passport version.');
+ }
+
$token = $this->tokens->find($tokenId);
+ if (!$token instanceof Token) {
+ return $response;
+ }
if ($token->client->firstParty() && LumenPassport::$allowMultipleTokens) {
// We keep previous tokens for password clients
| 13 | Add compatibility for `lcobucci/jwt` `^4.0` | 1 | .php | php | mit | dusterio/lumen-passport |
10067900 | <NME> integration.php
<BEF> <?php
namespace Dusterio\LumenPassport\Tests;
use Dusterio\LumenPassport\Http\Controllers\AccessTokenController;
use Dusterio\LumenPassport\LumenPassport;
use Carbon\Carbon;
use Laravel\Passport\Passport;
use Laravel\Passport\PassportServiceProvider;
/**
* Class IntegrationTest
* @package Dusterio\LumenPassport\Tests
*/
class IntegrationTest extends \PHPUnit_Framework_TestCase
{
/**
* @test
*/
public function token_ttl_can_be_set_via_lumen_class()
{
// Default (global) client
LumenPassport::tokensExpireIn(Carbon::now()->addYears(1));
$this->assertTrue(Passport::tokensExpireIn() == Carbon::now()->diff(Carbon::now()->addYears(1)));
$this->assertTrue(LumenPassport::tokensExpireIn() == Carbon::now()->diff(Carbon::now()->addYears(1)));
// Specific client
LumenPassport::tokensExpireIn(Carbon::now()->addYears(5), 2);
$this->assertTrue(LumenPassport::tokensExpireIn(null, 2) == Carbon::now()->diff(Carbon::now()->addYears(5)));
$this->assertTrue(LumenPassport::tokensExpireIn() == Carbon::now()->diff(Carbon::now()->addYears(1)));
$this->assertTrue(Passport::tokensExpireIn() == Carbon::now()->diff(Carbon::now()->addYears(1)));
}
}
<MSG> PHP 7.1 minimum version, Laravel 9 support
<DFF> @@ -2,32 +2,46 @@
namespace Dusterio\LumenPassport\Tests;
-use Dusterio\LumenPassport\Http\Controllers\AccessTokenController;
use Dusterio\LumenPassport\LumenPassport;
use Carbon\Carbon;
use Laravel\Passport\Passport;
-use Laravel\Passport\PassportServiceProvider;
+use PHPUnit\Framework\TestCase;
/**
* Class IntegrationTest
* @package Dusterio\LumenPassport\Tests
*/
-class IntegrationTest extends \PHPUnit_Framework_TestCase
+class IntegrationTest extends TestCase
{
+
/**
* @test
*/
- public function token_ttl_can_be_set_via_lumen_class()
+ public function global_token_ttl_can_be_set_via_lumen_class() {
+ $now = Carbon::now();
+ Carbon::setTestNow($now);
+ $expiryDate = $now->clone()->addYear();
+ LumenPassport::tokensExpireIn($expiryDate);
+ $this->assertEquals(Passport::tokensExpireIn(), Carbon::now()->diff($expiryDate));
+ $this->assertEquals(LumenPassport::tokensExpireIn(), Carbon::now()->diff($expiryDate));
+ }
+
+ /**
+ * @test
+ */
+ public function client_specific_token_ttl_can_be_set_via_lumen_class()
{
- // Default (global) client
- LumenPassport::tokensExpireIn(Carbon::now()->addYears(1));
- $this->assertTrue(Passport::tokensExpireIn() == Carbon::now()->diff(Carbon::now()->addYears(1)));
- $this->assertTrue(LumenPassport::tokensExpireIn() == Carbon::now()->diff(Carbon::now()->addYears(1)));
+ $clientId = 2;
+ $now = Carbon::now();
+ Carbon::setTestNow($now);
+ $clientExpiryDate = $now->clone()->addYears(5);
+ $defaultGlobalExpiryDate = $now->clone()->addYears(1);
+
+ LumenPassport::tokensExpireIn($clientExpiryDate, $clientId);
+ $this->assertEquals(LumenPassport::tokensExpireIn(null, $clientId), Carbon::now()->diff($clientExpiryDate));
- // Specific client
- LumenPassport::tokensExpireIn(Carbon::now()->addYears(5), 2);
- $this->assertTrue(LumenPassport::tokensExpireIn(null, 2) == Carbon::now()->diff(Carbon::now()->addYears(5)));
- $this->assertTrue(LumenPassport::tokensExpireIn() == Carbon::now()->diff(Carbon::now()->addYears(1)));
- $this->assertTrue(Passport::tokensExpireIn() == Carbon::now()->diff(Carbon::now()->addYears(1)));
+ # global TTL should still default to 1 year
+ $this->assertEquals(LumenPassport::tokensExpireIn(), Carbon::now()->diff($defaultGlobalExpiryDate));
+ $this->assertEquals(Passport::tokensExpireIn(), Carbon::now()->diff($defaultGlobalExpiryDate));
}
}
\ No newline at end of file
| 27 | PHP 7.1 minimum version, Laravel 9 support | 13 | .php | php | mit | dusterio/lumen-passport |
10067901 | <NME> fruitmachine.js
<BEF> /*jslint browser:true, node:true*/
/**
* FruitMachine
*
* Renders layouts/modules from a basic layout definition.
* If views require custom interactions devs can extend
* the basic functionality.
*
* @version 0.3.3
* @copyright The Financial Times Limited [All Rights Reserved]
* @author Wilson Page <[email protected]>
*/
'use strict';
/**
* Module Dependencies
*/
var mod = require('./module');
var define = require('./define');
var utils = require('utils');
var events = require('evt');
/**
* Creates a fruitmachine
*/
/*jslint browser:true, node:true*/
var View = (function() {
'use strict';
var module = {};
//var View = typeof exports === 'object' ? exports : root.View = {};
// Create local references to some native methods.
var slice = Array.prototype.slice;
var concat = Array.prototype.concat;
var has = Object.prototype.hasOwnProperty;
function mixin(original) {
// Loop over every argument after the first.
slice.call(arguments, 1).forEach(function(source) {
for (var prop in source) {
original[prop] = source[prop];
}
});
return original;
}
var uniqueId = (function() {
var i = 0;
return function(prefix) {
prefix = prefix || '';
return prefix + (++i * Math.round(Math.random() * 10000000));
};
}());
var splitter = /\s+/;
var Events = {
// Bind one or more space separated events, `events`, to a `callback`
// function. Passing `"all"` will bind the callback to all events fired.
on: function(events, callback, context) {
var calls, event, node, tail, list;
if (!callback) return this;
events = events.split(splitter);
calls = this._callbacks || (this._callbacks = {});
// Create an immutable callback list, allowing traversal during
// modification. The tail is an empty object that will always be used
// as the next node.
event = events.shift();
while (event) {
list = calls[event];
node = list ? list.tail : {};
node.next = tail = {};
node.context = context;
node.callback = callback;
calls[event] = {tail: tail, next: list ? list.next : node};
event = events.shift();
}
return this;
},
// Remove one or many callbacks. If `context` is null, removes all callbacks
// with that function. If `callback` is null, removes all callbacks for the
// event. If `events` is null, removes all bound callbacks for all events.
off: function(events, callback, context) {
var event, calls, node, tail, cb, ctx;
// No events, or removing *all* events.
if (!(calls = this._callbacks)) return;
if (!(events || callback || context)) {
delete this._callbacks;
return this;
}
// Loop through the listed events and contexts, splicing them out of the
// linked list of callbacks if appropriate.
events = events ? events.split(splitter) : Object.keys(calls);
while (event = events.shift()) {
node = calls[event];
delete calls[event];
if (!node || !(callback || context)) continue;
// Create a new list, omitting the indicated callbacks.
tail = node.tail;
while ((node = node.next) !== tail) {
cb = node.callback;
ctx = node.context;
if ((callback && cb !== callback) || (context && ctx !== context)) {
this.on(event, cb, ctx);
}
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(events) {
var event, node, calls, tail, args, all, rest;
if (!(calls = this._callbacks)) return this;
all = calls.all;
events = events.split(splitter);
rest = slice.call(arguments, 1);
// For each event, walk through the linked list of callbacks twice,
// first to trigger the event, then to trigger any `"all"` callbacks.
while (event = events.shift()) {
if (node = calls[event]) {
tail = node.tail;
while ((node = node.next) !== tail) {
node.callback.apply(node.context || this, rest);
}
}
if (node = all) {
tail = node.tail;
args = [event].concat(rest);
while ((node = node.next) !== tail) {
node.callback.apply(node.context || this, args);
}
}
}
return this;
}
};
var Modules = {};
function create(options) {
var Module = Modules[options.type];
if (!Module) return;
delete options.type;
return new Module(options);
}
/**
* VIEW
*/
var View = module.exports = function (options) {
if (options.type) return create(options);
this._configure(options);
this.add(options.views);
this.initialize(options);
};
// Extend the prototype
mixin(View.prototype, Events, {
_configure: function(options) {
this._id = options.id || uniqueId('auto_');
this._fmid = uniqueId('fmid');
this.model = options.model || {};
this._children = [];
this._lookup = {};
},
initialize: function() {},
add: function(views) {
if (!views) return;
var view;
views = concat.call([], views);
for (var i = 0, l = views.length; i < l; i++) {
view = views[i];
if (!(view instanceof View)) view = new View(view);
this._children.push(view);
this._lookup[view.id()] = view;
view.parent = this;
}
return this;
},
id: function(id) {
return id ? this._lookup[id] : this._id;
},
fmid: function() {
return this._fmid;
},
data: function() {
if (!this.model) return {};
if (this.model.toJSON) return this.model.toJSON();
return this.model;
},
children: function() {
return this._children;
},
html: function() {
var data = {};
var children = this.children();
var child, html;
data.views = [];
for (var i = 0, l = children.length; i < l; i++) {
child = children[i];
html = child.html();
data[child.id()] = html;
data.views.push({ view: html });
}
data.fm_attrs = 'id="' + this.fmid() + '"';
return this._html = this.template.render(mixin(data, this.data()));
},
render: function() {
return this.update();
},
setup: function() {
},
el: function() {
return this._el || (this._el = document.getElementById(this.fmid()));
},
update: function() {
var current = this.el();
var replacement = this.toNode();
if (!current && !current.parentNode) {
this._el = replacement;
return this;
}
current.parentNode.replaceChild(replacement, current);
this._el = replacement;
return this;
},
node: function() {
var el = document.createElement('div');
el.innerHTML = this.html();
return el.firstElementChild;
},
inject: function(dest) {
var el = this.el();
dest.innerHTML = '';
dest.appendChild(el);
}
});
View.register = function(type, modules) {
mixin(Modules, modules);
};
// Helpers
// -------
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
View.inherit = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && has.call(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
mixin(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate();
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) mixin(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
// We add the 'extend' static method to the FruitMachine base
// class. This allows you to extend the default View class
// to add custom insteractions and logic to more complex modules.
// Redefining any of the View.prototype methods will overwrite them.
View.extend = function(type, props) {
if ('string' === typeof type) {
return Modules[type] = View.inherit(props);
} else if ('object' === typeof type) {
return View.inherit(type);
}
};
// Current Version
View.VERSION = '0.0.1';
return module.exports;
}(this));
<MSG> - Progress on new api
<DFF> @@ -28,315 +28,558 @@
*/
/*jslint browser:true, node:true*/
-var View = (function() {
- 'use strict';
-
- var module = {};
- //var View = typeof exports === 'object' ? exports : root.View = {};
-
- // Create local references to some native methods.
- var slice = Array.prototype.slice;
- var concat = Array.prototype.concat;
- var has = Object.prototype.hasOwnProperty;
-
- function mixin(original) {
- // Loop over every argument after the first.
- slice.call(arguments, 1).forEach(function(source) {
- for (var prop in source) {
- original[prop] = source[prop];
- }
- });
- return original;
- }
-
- var uniqueId = (function() {
- var i = 0;
- return function(prefix) {
- prefix = prefix || '';
- return prefix + (++i * Math.round(Math.random() * 10000000));
- };
- }());
-
- var splitter = /\s+/;
- var Events = {
-
- // Bind one or more space separated events, `events`, to a `callback`
- // function. Passing `"all"` will bind the callback to all events fired.
- on: function(events, callback, context) {
-
- var calls, event, node, tail, list;
- if (!callback) return this;
- events = events.split(splitter);
- calls = this._callbacks || (this._callbacks = {});
-
- // Create an immutable callback list, allowing traversal during
- // modification. The tail is an empty object that will always be used
- // as the next node.
- event = events.shift();
- while (event) {
- list = calls[event];
- node = list ? list.tail : {};
- node.next = tail = {};
- node.context = context;
- node.callback = callback;
- calls[event] = {tail: tail, next: list ? list.next : node};
- event = events.shift();
- }
-
- return this;
- },
-
- // Remove one or many callbacks. If `context` is null, removes all callbacks
- // with that function. If `callback` is null, removes all callbacks for the
- // event. If `events` is null, removes all bound callbacks for all events.
- off: function(events, callback, context) {
- var event, calls, node, tail, cb, ctx;
-
- // No events, or removing *all* events.
- if (!(calls = this._callbacks)) return;
- if (!(events || callback || context)) {
- delete this._callbacks;
- return this;
- }
-
- // Loop through the listed events and contexts, splicing them out of the
- // linked list of callbacks if appropriate.
- events = events ? events.split(splitter) : Object.keys(calls);
- while (event = events.shift()) {
- node = calls[event];
- delete calls[event];
- if (!node || !(callback || context)) continue;
- // Create a new list, omitting the indicated callbacks.
- tail = node.tail;
- while ((node = node.next) !== tail) {
- cb = node.callback;
- ctx = node.context;
- if ((callback && cb !== callback) || (context && ctx !== context)) {
- this.on(event, cb, ctx);
- }
- }
- }
-
- return this;
- },
-
- // Trigger one or many events, firing all bound callbacks. Callbacks are
- // passed the same arguments as `trigger` is, apart from the event name
- // (unless you're listening on `"all"`, which will cause your callback to
- // receive the true name of the event as the first argument).
- trigger: function(events) {
- var event, node, calls, tail, args, all, rest;
- if (!(calls = this._callbacks)) return this;
- all = calls.all;
- events = events.split(splitter);
- rest = slice.call(arguments, 1);
-
- // For each event, walk through the linked list of callbacks twice,
- // first to trigger the event, then to trigger any `"all"` callbacks.
- while (event = events.shift()) {
- if (node = calls[event]) {
- tail = node.tail;
- while ((node = node.next) !== tail) {
- node.callback.apply(node.context || this, rest);
- }
- }
-
- if (node = all) {
- tail = node.tail;
- args = [event].concat(rest);
- while ((node = node.next) !== tail) {
- node.callback.apply(node.context || this, args);
- }
- }
- }
-
- return this;
- }
- };
-
-
- var Modules = {};
-
- function create(options) {
- var Module = Modules[options.type];
- if (!Module) return;
- delete options.type;
- return new Module(options);
- }
-
- /**
- * VIEW
- */
-
- var View = module.exports = function (options) {
- if (options.type) return create(options);
- this._configure(options);
- this.add(options.views);
- this.initialize(options);
- };
-
- // Extend the prototype
- mixin(View.prototype, Events, {
-
- _configure: function(options) {
- this._id = options.id || uniqueId('auto_');
- this._fmid = uniqueId('fmid');
- this.model = options.model || {};
- this._children = [];
- this._lookup = {};
- },
-
- initialize: function() {},
-
- add: function(views) {
- if (!views) return;
- var view;
-
- views = concat.call([], views);
-
- for (var i = 0, l = views.length; i < l; i++) {
- view = views[i];
- if (!(view instanceof View)) view = new View(view);
- this._children.push(view);
- this._lookup[view.id()] = view;
- view.parent = this;
- }
-
- return this;
- },
-
- id: function(id) {
- return id ? this._lookup[id] : this._id;
- },
-
- fmid: function() {
- return this._fmid;
- },
-
- data: function() {
- if (!this.model) return {};
- if (this.model.toJSON) return this.model.toJSON();
- return this.model;
- },
-
- children: function() {
- return this._children;
- },
-
- html: function() {
- var data = {};
- var children = this.children();
- var child, html;
- data.views = [];
-
- for (var i = 0, l = children.length; i < l; i++) {
- child = children[i];
- html = child.html();
- data[child.id()] = html;
- data.views.push({ view: html });
- }
-
- data.fm_attrs = 'id="' + this.fmid() + '"';
- return this._html = this.template.render(mixin(data, this.data()));
- },
-
- render: function() {
- return this.update();
- },
-
- setup: function() {
-
- },
-
- el: function() {
- return this._el || (this._el = document.getElementById(this.fmid()));
- },
-
- update: function() {
- var current = this.el();
- var replacement = this.toNode();
-
- if (!current && !current.parentNode) {
- this._el = replacement;
- return this;
- }
-
- current.parentNode.replaceChild(replacement, current);
- this._el = replacement;
- return this;
- },
-
- node: function() {
- var el = document.createElement('div');
- el.innerHTML = this.html();
- return el.firstElementChild;
- },
-
- inject: function(dest) {
- var el = this.el();
- dest.innerHTML = '';
- dest.appendChild(el);
- }
- });
-
-
- View.register = function(type, modules) {
- mixin(Modules, modules);
- };
-
- // Helpers
- // -------
-
- // Helper function to correctly set up the prototype chain, for subclasses.
- // Similar to `goog.inherits`, but uses a hash of prototype properties and
- // class properties to be extended.
- View.inherit = function(protoProps, staticProps) {
- var parent = this;
- var child;
-
- // The constructor function for the new subclass is either defined by you
- // (the "constructor" property in your `extend` definition), or defaulted
- // by us to simply call the parent's constructor.
- if (protoProps && has.call(protoProps, 'constructor')) {
- child = protoProps.constructor;
- } else {
- child = function(){ return parent.apply(this, arguments); };
- }
-
- // Add static properties to the constructor function, if supplied.
- mixin(child, parent, staticProps);
-
- // Set the prototype chain to inherit from `parent`, without calling
- // `parent`'s constructor function.
- var Surrogate = function(){ this.constructor = child; };
- Surrogate.prototype = parent.prototype;
- child.prototype = new Surrogate();
-
- // Add prototype properties (instance properties) to the subclass,
- // if supplied.
- if (protoProps) mixin(child.prototype, protoProps);
-
- // Set a convenience property in case the parent's prototype is needed
- // later.
- child.__super__ = parent.prototype;
-
- return child;
- };
-
- // We add the 'extend' static method to the FruitMachine base
- // class. This allows you to extend the default View class
- // to add custom insteractions and logic to more complex modules.
- // Redefining any of the View.prototype methods will overwrite them.
- View.extend = function(type, props) {
- if ('string' === typeof type) {
- return Modules[type] = View.inherit(props);
- } else if ('object' === typeof type) {
- return View.inherit(type);
- }
- };
-
- // Current Version
- View.VERSION = '0.0.1';
-
- return module.exports;
+var FruitMachine = (function(root) {
+ 'use strict';
+
+ /**
+ * VIEW
+ */
+
+ var FruitMachine = function(options) {
+ if (options.module) return create(options);
+ this._configure(options);
+ this.add(options.children);
+ this.onInitialize(options);
+ };
+
+ // Current Version
+ FruitMachine.VERSION = '0.0.1';
+
+ // Global data store
+ var store = {
+ modules: {},
+ templates: {},
+ helpers: {}
+ };
+
+ // Utilities
+ var util = FruitMachine.util = {
+
+ bind: function(method, context) {
+ return function() { return method.apply(context, arguments); };
+ },
+
+ bindAll: function(ob, context) {
+ for (var key in ob) {
+ if ('function' === typeof ob[key]) {
+ ob[key] = util.bind(ob[key], context);
+ }
+ }
+ },
+
+ mixin: function(original) {
+ // Loop over every argument after the first.
+ slice.call(arguments, 1).forEach(function(source) {
+ for (var prop in source) {
+ original[prop] = source[prop];
+ }
+ });
+ return original;
+ },
+
+ uniqueId: (function() {
+ var i = 0;
+ return function(prefix) {
+ prefix = prefix || '';
+ return prefix + (++i * Math.round(Math.random() * 10000000));
+ };
+ }())
+ };
+
+ // Create local references to some methods
+ var slice = Array.prototype.slice;
+ var concat = Array.prototype.concat;
+ var has = Object.prototype.hasOwnProperty;
+ var mixin = util.mixin;
+
+ var splitter = /\s+/;
+ var Events = FruitMachine.Events = {
+
+ // Bind one or more space separated events, `events`, to a `callback`
+ // function. Passing `"all"` will bind the callback to all events fired.
+ on: function(events, callback, context) {
+
+ var calls, event, node, tail, list;
+ if (!callback) return this;
+ events = events.split(splitter);
+ calls = this._callbacks || (this._callbacks = {});
+
+ // Create an immutable callback list, allowing traversal during
+ // modification. The tail is an empty object that will always be used
+ // as the next node.
+ event = events.shift();
+ while (event) {
+ list = calls[event];
+ node = list ? list.tail : {};
+ node.next = tail = {};
+ node.context = context;
+ node.callback = callback;
+ calls[event] = {tail: tail, next: list ? list.next : node};
+ event = events.shift();
+ }
+
+ return this;
+ },
+
+ // Remove one or many callbacks. If `context` is null, removes all callbacks
+ // with that function. If `callback` is null, removes all callbacks for the
+ // event. If `events` is null, removes all bound callbacks for all events.
+ off: function(events, callback, context) {
+ var event, calls, node, tail, cb, ctx;
+
+ // No events, or removing *all* events.
+ if (!(calls = this._callbacks)) return;
+ if (!(events || callback || context)) {
+ delete this._callbacks;
+ return this;
+ }
+
+ // Loop through the listed events and contexts, splicing them out of the
+ // linked list of callbacks if appropriate.
+ events = events ? events.split(splitter) : Object.keys(calls);
+ while (event = events.shift()) {
+ node = calls[event];
+ delete calls[event];
+ if (!node || !(callback || context)) continue;
+ // Create a new list, omitting the indicated callbacks.
+ tail = node.tail;
+ while ((node = node.next) !== tail) {
+ cb = node.callback;
+ ctx = node.context;
+ if ((callback && cb !== callback) || (context && ctx !== context)) {
+ this.on(event, cb, ctx);
+ }
+ }
+ }
+
+ return this;
+ },
+
+ // Trigger one or many events, firing all bound callbacks. Callbacks are
+ // passed the same arguments as `trigger` is, apart from the event name
+ // (unless you're listening on `"all"`, which will cause your callback to
+ // receive the true name of the event as the first argument).
+ trigger: function(events) {
+ var event, node, calls, tail, args, all, rest;
+ if (!(calls = this._callbacks)) return this;
+ all = calls.all;
+ events = events.split(splitter);
+ rest = slice.call(arguments, 1);
+
+ // For each event, walk through the linked list of callbacks twice,
+ // first to trigger the event, then to trigger any `"all"` callbacks.
+ while (event = events.shift()) {
+ if (node = calls[event]) {
+ tail = node.tail;
+ while ((node = node.next) !== tail) {
+ node.callback.apply(node.context || this, rest);
+ }
+ }
+
+ if (node = all) {
+ tail = node.tail;
+ args = [event].concat(rest);
+ while ((node = node.next) !== tail) {
+ node.callback.apply(node.context || this, args);
+ }
+ }
+ }
+
+ return this;
+ }
+ };
+
+
+ FruitMachine.helper = function(name, Helper) {
+ if (Helper.attach) Helper.attach(FruitMachine);
+ store.helpers[name] = Helper;
+ };
+
+
+ var getTemplate = function(module) {
+ return store.templates[module];
+ };
+
+ /**
+ * Registers templates, or overwrites
+ * the `getTemplate` method with a
+ * custom template getter function.
+ *
+ * @param {Object|Function} templates
+ * @return void
+ */
+ FruitMachine.templates = function(templates) {
+ var type = typeof templates;
+ if ('object' === type) mixin(store.templates, templates);
+ else if ('function' === type) getTemplate = templates;
+ };
+
+ // Manages helpers
+ var helper = {
+ attach: function(helper) {
+ var Helper = store.helpers[helper];
+ var Exports = Helper && Helper.exports;
+ if (!Exports) return;
+ if ('function' === typeof Exports) {
+ return this[helper] = new Exports(this);
+ } else {
+ return util.mixin(this, Exports);
+ }
+ },
+
+ setup: function(helper) {
+ if (!helper.onSetup) return;
+ helper.onSetup();
+ },
+
+ teardown: function(helper) {
+ if (!helper.onTeardown) return;
+ helper.onTeardown();
+ }
+ };
+
+ // Factory method
+ function create(options) {
+ var Module = store.modules[options.module] || FruitMachine;
+ options._module = options.module;
+ delete options.module;
+ return new Module(options);
+ }
+
+ // Extend the prototype
+ mixin(FruitMachine.prototype, Events, {
+
+ _configure: function(options) {
+ this._id = options.id || util.uniqueId('auto_');
+ this._fmid = options.fmid || util.uniqueId('fmid');
+ this.module = options._module;
+ this.model = options.model || {};
+ this._lookup = {};
+ this._children = [];
+ this._data = options.data || {};
+
+ // Use the template defined on
+ // the custom view, or use the
+ // template getter.
+ this.template = this.template || getTemplate(this.module);
+
+ // Upgrade helpers
+ this.helpers = (this.helpers || []).map(helper.attach, this);
+ },
+
+ onInitialize: function() {},
+ onSetup: function() {},
+ onTeardown: function() {},
+ onDestroy: function() {},
+
+ add: function(children) {
+ if (!children) return;
+ var child;
+
+ // Make sure it's an array
+ children = concat.call([], children);
+
+ for (var i = 0, l = children.length; i < l; i++) {
+ child = children[i];
+ if (!(child instanceof FruitMachine)) child = new FruitMachine(child);
+ this._children.push(child);
+ this.addLookup(child);
+ child.parent = this;
+ }
+
+ return this;
+ },
+
+ addLookup: function(child) {
+ this._lookup[child.id()] = child;
+ this._lookup[child.module] = this._lookup[child.module] || [];
+ this._lookup[child.module].push(child);
+ },
+
+ id: function(id) {
+ return id ? this._lookup[id] : this._id;
+ },
+
+ child: function(name) {
+ return this._lookup[name][0];
+ },
+
+ children: function(name) {
+ return name ? this._lookup[name] : this._children;
+ },
+
+ fmid: function() {
+ return this._fmid;
+ },
+
+ views: function() {
+ return this._views;
+ },
+
+ toHTML: function() {
+ var data = {};
+ var children = this.children();
+ var child, html;
+ data.children = [];
+
+ for (var i = 0, l = children.length; i < l; i++) {
+ child = children[i];
+ html = child.toHTML();
+ data[child.id()] = html;
+ data.children.push({ child: html });
+ }
+
+ data.fm_attrs = 'id="' + this.fmid() + '"';
+ return this._html = this.template.render(mixin(data, this.data()));
+ },
+
+ render: function() {
+ return this.update();
+ },
+
+ setup: function(options) {
+ var shallow = options && options.shallow;
+ var children = this.children();
+
+ // Call 'setup' on all subviews
+ // first (bottom up recursion).
+ if (!shallow) {
+ for (var i = 0, l = children.length; i < l; i++) {
+ children[i].setup();
+ }
+ }
+
+ // Setup any helpers
+ this.helpers.forEach(helper.setup, this);
+
+ this.onSetup();
+ this.trigger('setup');
+ this.isSetup = true;
+
+ // For chaining
+ return this;
+ },
+
+ teardown: function(options) {
+ var shallow = options && options.shallow;
+ var children = this.children();
+
+ // Call 'setup' on all subviews
+ // first (bottom up recursion).
+ if (!shallow) {
+ for (var i = 0, l = children.length; i < l; i++) {
+ children[i].teardown();
+ }
+ }
+
+ // Teardown any helpers
+ this.helpers.forEach(helper.teardown, this);
+
+ this.trigger('teardown');
+ this.onTeardown();
+ this.isSetup = false;
+
+ // For chaining
+ return this;
+ },
+
+ destroy: function(options) {
+
+ // Recursively run on children
+ // first (bottom up).
+ //
+ // We don't waste time removing
+ // the child elements as they will
+ // get removed when the parent
+ // element is removed.
+ while (this._children.length) {
+ this._children[0].destroy({ skipEl: true });
+ }
+
+ // Run teardown so custom
+ // views can bind logic to it
+ this.teardown(options);
+
+ // Detach this view from its
+ // parent and unless otherwise
+ // stated, from the DOM.
+ //this._detach(options);
+
+ // Trigger a destroy event
+ // for custom Views to bind to.
+ this.trigger('destroy');
+ this.onDestroy();
+
+ // 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.module = this._id = this._lookup = null;
+ },
+
+ _detach: function() {
+
+ },
+
+ el: function() {
+ return this._el || (this._el = document.getElementById(this.fmid()));
+ },
+
+ /**
+ * A single method for getting
+ * and setting view data.
+ *
+ * Example:
+ *
+ * // Getters
+ * var all = view.data();
+ * var one = view.data('myKey');
+ *
+ * // Setters
+ * view.data('myKey', 'my value');
+ * view.data({
+ * myKey: 'my value',
+ * anotherKey: 10
+ * });
+ *
+ * @param {String|Object|null} key
+ * @param {*} value
+ * @return {*}
+ */
+
+ data: function(key, value) {
+
+ // If no key and no value have
+ // been passed then return the
+ // entire data store.
+ if (!key && !value) {
+ return this._data;
+ }
+
+ // If a string key has been
+ // passed, but no value
+ if (typeof key === 'string' && !value) {
+ return this._data[key];
+ }
+
+ // If the user has stated a key
+ // and a value. Set the value on
+ // the key.
+ if (key && value) {
+ this._data[key] = value;
+ this.trigger('datachange', key, value);
+ this.trigger('datachange:' + key, value);
+ return this;
+ }
+
+ // If the key is an object literal
+ // then we extend the data store with it.
+ if ('object' === typeof key) {
+ mixin(this._data, key);
+ this.trigger('datachange');
+ for (var prop in key) this.trigger('datachange:' + prop, key[prop]);
+ return this;
+ }
+ },
+
+ update: function() {
+ var current = this.el();
+ var replacement = this.toNode();
+
+ if (!current) {
+ this._el = replacement;
+ return this;
+ }
+
+ current.parentNode.replaceChild(replacement, current);
+ this._el = replacement;
+ return this;
+ },
+
+ toNode: function() {
+ var el = document.createElement('div');
+ el.innerHTML = this.toHTML();
+ return el.firstElementChild;
+ },
+
+ inject: function(dest) {
+ var el = this.el();
+ dest.innerHTML = '';
+ dest.appendChild(el);
+ return this;
+ },
+
+ toJSON: function() {
+ var json = {};
+ var children = this.children();
+ json.children = [];
+
+ // Recurse
+ for (var i = 0, l = children.length; i < l; i++) {
+ json.children.push(children[i].toJSON());
+ }
+
+ json.id = this.id();
+ json.fmid = this.fmid();
+ json.model = this.data();
+ return json;
+ }
+ });
+
+ // Helpers
+ // -------
+
+ // Helper function to correctly set up the prototype chain, for subclasses.
+ // Similar to `goog.inherits`, but uses a hash of prototype properties and
+ // class properties to be extended.
+ FruitMachine.inherit = function(protoProps, staticProps) {
+ var parent = this;
+ var child;
+
+ // The constructor function for the new subclass is either defined by you
+ // (the "constructor" property in your `extend` definition), or defaulted
+ // by us to simply call the parent's constructor.
+ if (protoProps && has.call(protoProps, 'constructor')) {
+ child = protoProps.constructor;
+ } else {
+ child = function(){ return parent.apply(this, arguments); };
+ }
+
+ // Add static properties to the constructor function, if supplied.
+ mixin(child, parent, staticProps);
+
+ // Set the prototype chain to inherit from `parent`, without calling
+ // `parent`'s constructor function.
+ var Surrogate = function(){ this.constructor = child; };
+ Surrogate.prototype = parent.prototype;
+ child.prototype = new Surrogate();
+
+ // Add prototype properties (instance properties) to the subclass,
+ // if supplied.
+ if (protoProps) mixin(child.prototype, protoProps);
+
+ // Set a convenience property in case the parent's prototype is needed
+ // later.
+ child.__super__ = parent.prototype;
+
+ return child;
+ };
+
+ // We add the 'extend' static method to the FruitMachine base
+ // class. This allows you to extend the default View class
+ // to add custom insteractions and logic to more complex modules.
+ // Redefining any of the View.prototype methods will overwrite them.
+ FruitMachine.module = function(type, props) {
+ if ('string' === typeof type) {
+ return store.modules[type] = FruitMachine.inherit(props);
+ } else if ('object' === typeof type) {
+ return FruitMachine.inherit(type);
+ }
+ };
+
+ return FruitMachine;
}(this));
\ No newline at end of file
| 554 | - Progress on new api | 311 | .js | js | mit | ftlabs/fruitmachine |
10067902 | <NME> tests.js
<BEF> /**
* loadjs tests
* @module test/tests.js
*/
var pathsLoaded = null, // file register
testEl = null,
assert = chai.assert,
expect = chai.expect;
describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
// reset loadjs dependencies
loadjs.reset();
});
// ==========================================================================
// JavaScript file loading tests
// ==========================================================================
describe('JavaScript file loading tests', function() {
it('should call success callback on valid path', function(done) {
loadjs(['assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
}
});
});
it('should call fail callback on invalid path', function(done) {
loadjs(['assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
fail: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should call before callback before embedding into document', function(done) {
var scriptTags = [];
loadjs(['assets/file1.js', 'assets/file2.js'], {
before: function(path, el) {
scriptTags.push({
path: path,
el: el
});
it('should call fail callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
fail: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
assert.equal(scriptTags[1].el.crossOrigin, 'anonymous');
done();
}
});
});
it('should bypass insertion if before returns `false`', function(done) {
loadjs(['assets/file1.js'], {
before: function(path, el) {
// append to body (instead of head)
document.body.appendChild(el);
// return `false` to bypass default DOM insertion
return false;
},
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
// verify that file was added to body
var els = document.body.querySelectorAll('script'),
el;
for (var i=0; i < els.length; i++) {
el = els[i];
if (el.src.indexOf('assets/file1.js') !== -1) done();
}
}
});
});
it('should call success callback on two valid paths', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should support async false', function(done) {
success: function() {
throw "Executed success callback";
},
fail: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], blockedScript);
var testFn = function(paths) {
// add cache busters
var pathsUncached = paths.slice(0);
pathsUncached[0] += '?_=' + Math.random();
pathsUncached[1] += '?_=' + Math.random();
loadjs(pathsUncached, {
success: function() {
var f1 = paths[0].replace('assets/', '');
var f2 = paths[1].replace('assets/', '');
// check load order
assert.isTrue(pathsLoaded[f1]);
assert.isFalse(pathsLoaded[f2]);
// increment tests
numCompleted += 1;
if (numCompleted === numTests) {
// exit
done();
} else {
// reset register
pathsLoaded = {};
// run test again
paths.reverse();
testFn(paths);
}
},
async: false
});
};
// run tests
testFn(paths);
});
it('should support multiple tries', function(done) {
loadjs('assets/file-numretries.js', {
error: function() {
// check number of scripts in document
var selector = 'script[src="assets/file-numretries.js"]',
scripts = document.querySelectorAll(selector);
if (scripts.length === 2) done();
},
numRetries: 1
});
});
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
// custom filter under Options
//
});
it('should call fail callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw "Executed success callback";
},
fail: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
assert.equal(pathsNotFound[1], s2);
done();
}
});
});
});
// ==========================================================================
// CSS file loading tests
// ==========================================================================
describe('CSS file loading tests', function() {
before(function() {
// add test div to body for css tests
testEl = document.createElement('div');
testEl.className = 'test-div mui-container';
testEl.style.display = 'inline-block';
document.body.appendChild(testEl);
});
afterEach(function() {
var els = document.getElementsByTagName('link'),
i = els.length,
el;
});
it('should call failure on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw "Executed success callback";
},
fail: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
loadjs(['assets/file1.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/file1.css', 'assets/file2.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 200);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
done();
}
});
});
it('should support mix of css and js', function(done) {
loadjs(['assets/file1.css', 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should support forced "css!" files', function(done) {
loadjs(['css!assets/file1.css'], {
success: function() {
// loop through files
var els = document.getElementsByTagName('link'),
i = els.length,
el;
while (i--) {
if (els[i].href.indexOf('file1.css') !== -1) done();
}
}
});
});
it('supports urls with query arguments', function(done) {
loadjs(['assets/file1.css?x=x'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
loadjs(['assets/file1.css#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
});
it('should fail on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle9');
loadjs('assets/file-doesntexist.js', 'bundle10');
});
success: function() {
throw "Executed success callback";
},
fail: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle10');
success: function() {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '15px');
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
done();
}
});
});
// teardown
return after(function() {
// remove test div
testEl.parentNode.removeChild(testEl);
});
});
// ==========================================================================
// Image file loading tests
// ==========================================================================
describe('Image file loading tests', function() {
function assertLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// verify image was loaded
if (img.src === src) assert.equal(img.naturalWidth > 0, true);
});
}
function assertNotLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// fail if image was loaded
if (img.src === src) assert.equal(img.naturalWidth, 0);
});
}
it('should load one file', function(done) {
loadjs(['assets/flash.png'], {
success: function() {
assertLoaded('assets/flash.png');
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/flash.png', 'assets/flash.jpg'], {
success: function() {
assertLoaded('assets/flash.png');
assertLoaded('assets/flash.jpg');
done();
}
});
});
it('detects png|gif|jpg|svg|webp extensions', function(done) {
let files = [
'assets/flash.png',
'assets/flash.gif',
'assets/flash.jpg',
'assets/flash.svg',
'assets/flash.webp'
];
loadjs(files, function() {
files.forEach(file => {assertLoaded(file);});
done();
});
});
it('supports urls with query arguments', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
var src = 'assets/flash.png#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
var src = 'assets/flash.png';
src += '?' + Math.random();
src += '#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should support forced "img!" files', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
var src1 = 'assets/flash.png?' + Math.random(),
src2 = 'assets/flash-doesntexist.png?' + Math.random();
loadjs(['img!' + src1, 'img!' + src2], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assertLoaded(src1);
assertNotLoaded(src2);
done();
}
});
});
it('should support mix of img and js', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src, 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assertLoaded(src);
done();
}
});
});
it('should load external img files', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/mui-logo.png?';
src += Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/';
src += 'mui-logo-doesntexist.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assertNotLoaded(src);
done();
}
});
});
});
// ==========================================================================
// API tests
// ==========================================================================
describe('API tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle');
};
expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should chain loadjs object', function(done) {
function bothDone() {
if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done();
}
// define bundles
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs
.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
}
});
});
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file-doesntexist.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
});
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
// execute done
loadjs.done('plugin');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
loadjs.done('plugin');
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
}, 1000);
});
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
// use 1 second delay
setTimeout(function() {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
}, 1000);
});
it('should reset dependencies statuses', function() {
loadjs(['assets/file1.js'], 'cleared');
loadjs.reset();
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'cleared');
};
expect(fn).not.to.throw("LoadJS");
});
it('should indicate if bundle has already been defined', function() {
loadjs(['assets/file1/js'], 'bundle1');
assert.equal(loadjs.isDefined('bundle1'), true);
assert.equal(loadjs.isDefined('bundleXX'), false);
});
it('should accept success callback functions to loadjs()', function(done) {
loadjs('assets/file1.js', function() {
done();
});
});
it('should accept success callback functions to .ready()', function(done) {
loadjs.done('plugin');
loadjs.ready('plugin', function() {
done();
});
});
it('should return Promise object if returnPromise is true', function() {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
// verify that response object is a Promise
assert.equal(prom instanceof Promise, true);
});
it('Promise object should support resolutions', function(done) {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
prom.then(function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('Promise object should support rejections', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom.then(
function(){},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
);
});
it('Promise object should support catches', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom
.catch(function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('supports Promises and success callbacks', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
var prom = loadjs('assets/file1.js', {
success: completedFn,
returnPromise: true
});
prom.then(completedFn);
});
it('supports Promises and bundle ready events', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
.then(completedFn);
loadjs.ready('bundle1', completedFn);
});
});
});
<MSG> changed 'fail' callback name to 'error'
<DFF> @@ -35,12 +35,12 @@ describe('LoadJS tests', function() {
});
- it('should call fail callback on invalid path', function(done) {
+ it('should call error callback on invalid path', function(done) {
loadjs(['assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
- fail: function(pathsNotFound) {
+ error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
@@ -60,12 +60,12 @@ describe('LoadJS tests', function() {
});
- it('should call fail callback on one invalid path', function(done) {
+ it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
- fail: function(pathsNotFound) {
+ error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
@@ -132,7 +132,7 @@ describe('LoadJS tests', function() {
success: function() {
throw "Executed success callback";
},
- fail: function(pathsNotFound) {
+ error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], blockedScript);
@@ -196,12 +196,12 @@ describe('LoadJS tests', function() {
});
- it('should call fail callback on one invalid path', function(done) {
+ it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw "Executed success callback";
},
- fail: function(pathsNotFound) {
+ error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
@@ -235,14 +235,14 @@ describe('LoadJS tests', function() {
});
- it('should call failure on missing external file', function(done) {
+ it('should call errorure on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw "Executed success callback";
},
- fail: function(pathsNotFound) {
+ error: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
@@ -329,7 +329,7 @@ describe('LoadJS tests', function() {
});
- it('should fail on missing depdendencies', function(done) {
+ it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle9');
loadjs('assets/file-doesntexist.js', 'bundle10');
@@ -337,7 +337,7 @@ describe('LoadJS tests', function() {
success: function() {
throw "Executed success callback";
},
- fail: function(depsNotFound) {
+ error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle10');
| 11 | changed 'fail' callback name to 'error' | 11 | .js | js | mit | muicss/loadjs |
10067903 | <NME> tests.js
<BEF> /**
* loadjs tests
* @module test/tests.js
*/
var pathsLoaded = null, // file register
testEl = null,
assert = chai.assert,
expect = chai.expect;
describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
// reset loadjs dependencies
loadjs.reset();
});
// ==========================================================================
// JavaScript file loading tests
// ==========================================================================
describe('JavaScript file loading tests', function() {
it('should call success callback on valid path', function(done) {
loadjs(['assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
}
});
});
it('should call fail callback on invalid path', function(done) {
loadjs(['assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
fail: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should call before callback before embedding into document', function(done) {
var scriptTags = [];
loadjs(['assets/file1.js', 'assets/file2.js'], {
before: function(path, el) {
scriptTags.push({
path: path,
el: el
});
it('should call fail callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
fail: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
assert.equal(scriptTags[1].el.crossOrigin, 'anonymous');
done();
}
});
});
it('should bypass insertion if before returns `false`', function(done) {
loadjs(['assets/file1.js'], {
before: function(path, el) {
// append to body (instead of head)
document.body.appendChild(el);
// return `false` to bypass default DOM insertion
return false;
},
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
// verify that file was added to body
var els = document.body.querySelectorAll('script'),
el;
for (var i=0; i < els.length; i++) {
el = els[i];
if (el.src.indexOf('assets/file1.js') !== -1) done();
}
}
});
});
it('should call success callback on two valid paths', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should support async false', function(done) {
success: function() {
throw "Executed success callback";
},
fail: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], blockedScript);
var testFn = function(paths) {
// add cache busters
var pathsUncached = paths.slice(0);
pathsUncached[0] += '?_=' + Math.random();
pathsUncached[1] += '?_=' + Math.random();
loadjs(pathsUncached, {
success: function() {
var f1 = paths[0].replace('assets/', '');
var f2 = paths[1].replace('assets/', '');
// check load order
assert.isTrue(pathsLoaded[f1]);
assert.isFalse(pathsLoaded[f2]);
// increment tests
numCompleted += 1;
if (numCompleted === numTests) {
// exit
done();
} else {
// reset register
pathsLoaded = {};
// run test again
paths.reverse();
testFn(paths);
}
},
async: false
});
};
// run tests
testFn(paths);
});
it('should support multiple tries', function(done) {
loadjs('assets/file-numretries.js', {
error: function() {
// check number of scripts in document
var selector = 'script[src="assets/file-numretries.js"]',
scripts = document.querySelectorAll(selector);
if (scripts.length === 2) done();
},
numRetries: 1
});
});
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
// custom filter under Options
//
});
it('should call fail callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw "Executed success callback";
},
fail: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
assert.equal(pathsNotFound[1], s2);
done();
}
});
});
});
// ==========================================================================
// CSS file loading tests
// ==========================================================================
describe('CSS file loading tests', function() {
before(function() {
// add test div to body for css tests
testEl = document.createElement('div');
testEl.className = 'test-div mui-container';
testEl.style.display = 'inline-block';
document.body.appendChild(testEl);
});
afterEach(function() {
var els = document.getElementsByTagName('link'),
i = els.length,
el;
});
it('should call failure on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw "Executed success callback";
},
fail: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
loadjs(['assets/file1.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/file1.css', 'assets/file2.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 200);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
done();
}
});
});
it('should support mix of css and js', function(done) {
loadjs(['assets/file1.css', 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should support forced "css!" files', function(done) {
loadjs(['css!assets/file1.css'], {
success: function() {
// loop through files
var els = document.getElementsByTagName('link'),
i = els.length,
el;
while (i--) {
if (els[i].href.indexOf('file1.css') !== -1) done();
}
}
});
});
it('supports urls with query arguments', function(done) {
loadjs(['assets/file1.css?x=x'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
loadjs(['assets/file1.css#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
});
it('should fail on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle9');
loadjs('assets/file-doesntexist.js', 'bundle10');
});
success: function() {
throw "Executed success callback";
},
fail: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle10');
success: function() {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '15px');
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
done();
}
});
});
// teardown
return after(function() {
// remove test div
testEl.parentNode.removeChild(testEl);
});
});
// ==========================================================================
// Image file loading tests
// ==========================================================================
describe('Image file loading tests', function() {
function assertLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// verify image was loaded
if (img.src === src) assert.equal(img.naturalWidth > 0, true);
});
}
function assertNotLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// fail if image was loaded
if (img.src === src) assert.equal(img.naturalWidth, 0);
});
}
it('should load one file', function(done) {
loadjs(['assets/flash.png'], {
success: function() {
assertLoaded('assets/flash.png');
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/flash.png', 'assets/flash.jpg'], {
success: function() {
assertLoaded('assets/flash.png');
assertLoaded('assets/flash.jpg');
done();
}
});
});
it('detects png|gif|jpg|svg|webp extensions', function(done) {
let files = [
'assets/flash.png',
'assets/flash.gif',
'assets/flash.jpg',
'assets/flash.svg',
'assets/flash.webp'
];
loadjs(files, function() {
files.forEach(file => {assertLoaded(file);});
done();
});
});
it('supports urls with query arguments', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
var src = 'assets/flash.png#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
var src = 'assets/flash.png';
src += '?' + Math.random();
src += '#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should support forced "img!" files', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
var src1 = 'assets/flash.png?' + Math.random(),
src2 = 'assets/flash-doesntexist.png?' + Math.random();
loadjs(['img!' + src1, 'img!' + src2], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assertLoaded(src1);
assertNotLoaded(src2);
done();
}
});
});
it('should support mix of img and js', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src, 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assertLoaded(src);
done();
}
});
});
it('should load external img files', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/mui-logo.png?';
src += Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/';
src += 'mui-logo-doesntexist.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assertNotLoaded(src);
done();
}
});
});
});
// ==========================================================================
// API tests
// ==========================================================================
describe('API tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle');
};
expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should chain loadjs object', function(done) {
function bothDone() {
if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done();
}
// define bundles
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs
.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
}
});
});
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file-doesntexist.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
});
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
// execute done
loadjs.done('plugin');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
loadjs.done('plugin');
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
}, 1000);
});
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
// use 1 second delay
setTimeout(function() {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
}, 1000);
});
it('should reset dependencies statuses', function() {
loadjs(['assets/file1.js'], 'cleared');
loadjs.reset();
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'cleared');
};
expect(fn).not.to.throw("LoadJS");
});
it('should indicate if bundle has already been defined', function() {
loadjs(['assets/file1/js'], 'bundle1');
assert.equal(loadjs.isDefined('bundle1'), true);
assert.equal(loadjs.isDefined('bundleXX'), false);
});
it('should accept success callback functions to loadjs()', function(done) {
loadjs('assets/file1.js', function() {
done();
});
});
it('should accept success callback functions to .ready()', function(done) {
loadjs.done('plugin');
loadjs.ready('plugin', function() {
done();
});
});
it('should return Promise object if returnPromise is true', function() {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
// verify that response object is a Promise
assert.equal(prom instanceof Promise, true);
});
it('Promise object should support resolutions', function(done) {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
prom.then(function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('Promise object should support rejections', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom.then(
function(){},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
);
});
it('Promise object should support catches', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom
.catch(function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('supports Promises and success callbacks', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
var prom = loadjs('assets/file1.js', {
success: completedFn,
returnPromise: true
});
prom.then(completedFn);
});
it('supports Promises and bundle ready events', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
.then(completedFn);
loadjs.ready('bundle1', completedFn);
});
});
});
<MSG> changed 'fail' callback name to 'error'
<DFF> @@ -35,12 +35,12 @@ describe('LoadJS tests', function() {
});
- it('should call fail callback on invalid path', function(done) {
+ it('should call error callback on invalid path', function(done) {
loadjs(['assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
- fail: function(pathsNotFound) {
+ error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
@@ -60,12 +60,12 @@ describe('LoadJS tests', function() {
});
- it('should call fail callback on one invalid path', function(done) {
+ it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
- fail: function(pathsNotFound) {
+ error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
@@ -132,7 +132,7 @@ describe('LoadJS tests', function() {
success: function() {
throw "Executed success callback";
},
- fail: function(pathsNotFound) {
+ error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], blockedScript);
@@ -196,12 +196,12 @@ describe('LoadJS tests', function() {
});
- it('should call fail callback on one invalid path', function(done) {
+ it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw "Executed success callback";
},
- fail: function(pathsNotFound) {
+ error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
@@ -235,14 +235,14 @@ describe('LoadJS tests', function() {
});
- it('should call failure on missing external file', function(done) {
+ it('should call errorure on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw "Executed success callback";
},
- fail: function(pathsNotFound) {
+ error: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
@@ -329,7 +329,7 @@ describe('LoadJS tests', function() {
});
- it('should fail on missing depdendencies', function(done) {
+ it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle9');
loadjs('assets/file-doesntexist.js', 'bundle10');
@@ -337,7 +337,7 @@ describe('LoadJS tests', function() {
success: function() {
throw "Executed success callback";
},
- fail: function(depsNotFound) {
+ error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle10');
| 11 | changed 'fail' callback name to 'error' | 11 | .js | js | mit | muicss/loadjs |
10067904 | <NME> module.module.js
<BEF>
describe('View#module()', function() {
var viewToTest;
beforeEach(function() {
var layout = new Layout({});
var apple = new Apple({ slot: 1 });
var orange = new Orange({ slot: 2 });
var pear = new Pear({ slot: 3 });
layout
.add(apple)
.add(orange)
.add(pear);
viewToTest = layout;
});
test("Should return module type if no arguments given", function() {
expect(viewToTest.module()).toBe('layout');
});
test("Should return the first child module with the specified type.", function() {
var child = viewToTest.module('pear');
expect(child).toBe(viewToTest.children[2]);
});
test("If there is more than one child of this module type, only the first is returned.", function() {
viewToTest
.add({ module: 'apple' });
var child = viewToTest.module('apple');
var firstChild = viewToTest.children[0];
var lastChild = viewToTest.children[viewToTest.children.length-1];
expect(child).toBe(firstChild);
expect(child).not.toEqual(lastChild);
});
test("Should return the module name if defined with the name key", function() {
var Henry = fruitmachine.define({ name: 'henry' });
var henry = new Henry();
expect(henry.module()).toBe('henry');
expect(henry.name).toBe('henry');
});
test("Should walk down the fruitmachine tree, recursively", function() {
var Elizabeth = fruitmachine.define({ name: 'elizabeth' });
var elizabeth = new Elizabeth();
viewToTest.module('apple').add(elizabeth);
assert.equals(elizabethInstance.name, 'elizabeth');
},
"Should still recurse even if the root view used to have a module of the same type": function() {
var pear = this.view.module('pear').remove();
this.view.module('apple').add(pear);
var pear = viewToTest.module('pear').remove();
viewToTest.module('apple').add(pear);
var pearInstance = viewToTest.module('pear');
expect(pearInstance.module()).toBe('pear');
expect(pearInstance.name).toBe('pear');
});
});
<MSG> Add note to make it clear 2nd test is a regression test
<DFF> @@ -53,7 +53,7 @@ buster.testCase('View#module()', {
assert.equals(elizabethInstance.name, 'elizabeth');
},
- "Should still recurse even if the root view used to have a module of the same type": function() {
+ "Regression Test: Should still recurse even if the root view used to have a module of the same type": function() {
var pear = this.view.module('pear').remove();
this.view.module('apple').add(pear);
| 1 | Add note to make it clear 2nd test is a regression test | 1 | .js | module | mit | ftlabs/fruitmachine |
10067905 | <NME> fruitmachine.js <BEF> /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * @author Wilson Page <[email protected]> */ /*jslint browser:true, node:true*/ (function() { 'use strict'; var FruitMachine = function(options) { return new View(options); }; // Current Version FruitMachine.VERSION = '0.0.1'; // Global data store var store = FruitMachine.store = { modules: {}, templates: {}, helpers: {} }; // Create local references to some methods var slice = Array.prototype.slice; var has = Object.prototype.hasOwnProperty; * @param {Object} options * @return {Module} // in the current environment. var hasDom = (typeof document !== 'undefined'); // Utilities var util = FruitMachine.util = { bind: function(method, context) { return function() { return method.apply(context, arguments); }; }, bindAll: function(ob, context) { for (var key in ob) { if ('function' === typeof ob[key]) { ob[key] = util.bind(ob[key], context); } } }, isArray: function(arg) { return arg instanceof Array; }, fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; // Alias frequently used utils var mixin = util.mixin; /** * Events */ var splitter = /\s+/; var Events = FruitMachine.Events = { // Bind one or more space separated events, `events`, to a `callback` // function. Passing `"all"` will bind the callback to all events fired. }; /** * Creates and registers a * FruitMachine view constructor. * * @param {Object|View} * @return {View} */ FruitMachine.module = function(props) { var module = props.module || 'undefined'; var View; // Remove the module key delete props.module; // If an existing FruitMachine.View // has been passed in, use that. // If just an object literal has // been passed in then we extend the // default FruitMachine.View prototype // with the properties passed in. View = (props.__super__) ? props : FruitMachine.View.extend(props); // Make sure we explicity set the // `prototype._module` so that // `this._module` returns the correct // module type and not one further // down the prototype chain. View.prototype._module = module; // Store the module by module type // so that module can be referred to // by just a string in layout definitions return store.modules[module] = View; }; /** * Removes a module * from the module store. * * If no module key is passed * the entire store is cleared. * * @param {String|undefined} module * @api public */ FruitMachine.module.clear = function(module) { if (module) delete store.modules[module]; else store.modules = {}; }; /** * Helpers */ /** * Registers a helper * * @param {String} name * @param {Function} helper * @return void */ FruitMachine.helper = function(name, helper) { store.helpers[name] = helper; }; /** * Clears one or all * registered helpers. * * @param {String} name * @api public */ FruitMachine.helper.clear = function(name) { if (name) delete store.helpers[name]; else store.helpers = {}; }; /** * Templates */ /** * Registers templates, or overwrites * the `getTemplate` method with a * custom template getter function. * * @param {Object|Function} templates * @return void */ FruitMachine.templates = function(templates) { var type = typeof templates; if ('object' === type) mixin(store.templates, templates); else if ('function' === type) FruitMachine.templates.get = templates; }; /** * The default get template method * if FruitMachine.template is passed * a function, this gets overwritten * by that. * * @param {String} module * @return {Template} */ var getTemplate = FruitMachine.templates.get = function(module) { return store.templates[module]; }; /** * Clear reference to a module's * template, or clear all template * references and resets the template * getter method. * * @param {String|undefined} module * @api public */ FruitMachine.templates.clear = function(module) { if (module) delete store.templates[module]; else { store.templates = {}; FruitMachine.templates.get = getTemplate; } }; /** * View * @param {Object} options * @api public */ var View = FruitMachine.View = function(options) { // Shallow clone the options options = mixin({}, options); // Run initialize hooks this.onInitialize(options); this.trigger('initialize', [options], { propagate: false }); }; /** * Creates a new FruitMachine view this.propagate = false; }; // Extend the prototype mixin(View.prototype, { /** * Configures the new View * with the options passed * to the constructor. * * @param {Object} options * @api private */ _configure: function(options) { this._id = options.id || util.uniqueId('auto_'); this._fmid = options.fmid || util.uniqueId('fmid'); this.tag = options.tag || this.tag || 'div'; this.classes = this.classes || options.classes || []; this._module = this._module || options._module; this.helpers = this.helpers || options.helpers || []; this.template = this.getTemplate(); this._lookup = {}; this._children = []; // Use the model passed in, // or create a model from // the data passed in. this.model = options.model || new Model(options.data || {}); // Attach helpers this.helpers.forEach(this.attachHelper, this); // Purge html caches when the model is changed this.purgeHtmlCache = util.bind(this.purgeHtmlCache, this); this.model.on('change', this.purgeHtmlCache); }, // Events on: Events.on, off: Events.off, /** * Proxies the standard Event.trigger * method so that we can add bubble * functionality. * * Options: * * - `propagate` States whether the event * should bubble through parent views. * * @param {String} key * @param {Array} args * @param {Object} options * @return {View} * @api public */ trigger: function(key, args, event) { var propagate; // event can be passed as // the second or third argument if (!util.isArray(args)) { event = args; args = []; } // Use the event object passed // in, or make a fresh one event = event || { target: this, stopPropagation: stopPropagation }; // Trigger event Events.trigger.apply(this, [key, event].concat(args)); // Propagate by default propagate = (event.propagate !== false); // Trigger the same // event on the parent view if (propagate && this.parent) this.parent.trigger(key, args, event); // Allow chaining return this; }, // Empty methods you can overwrite // in your custom view logic. onInitialize: function() {}, onSetup: function() {}, onTeardown: function() {}, onDestroy: function() {}, attachHelper: function(helper) { // Allow helpers to be passed in as // string references to earlier registered // helpers, or passed in directly as a function. helper = ('function' === typeof helper) ? helper : store.helpers[helper]; // Run the helper function if (helper) helper(this, FruitMachine); }, getTemplate: function() { // Use the template defined on the // custom view, or use the template getter. var template = this.template || FruitMachine.templates.get(this._module); // Warn if no template found if (!template) return console.warn('FM - No template for %s', this._module); // Accomodate for template.render() or template() // this.template.render has to be bound to stop // a hogan.js error if the context is wrong. return template.render ? util.bind(template.render, template) : template; }, add: function(children, options) { var at = options && options.at; var inject = options && options.inject; var child; if (!children) return; // Make sure it's an array children = [].concat(children); for (var i = 0, l = children.length; i < l; i++) { child = children[i]; if (!(child instanceof View)) child = new View(child); util.insert(child, this._children, at); this._addLookup(child); child.parent = this; // 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.injectElement(child.el, options); } this.purgeHtmlCache(); return this; }, _addLookup: function(child) { this._lookup[child.id()] = child; this._lookup[child._module] = this._lookup[child._module] || []; this._lookup[child._module].push(child); }, _removeLookup: function(child) { var index = this._lookup[child._module].indexOf(child); this._lookup[child._module].splice(index, 1); delete this._lookup[child._id]; }, injectElement: 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. * * @param {String|undefined} id * @return {View|String} * @api public */ id: function(id) { return id ? this.module(id) : this._id; }, /** * Returns the first child * view that matches the query. * * Example: * * var child = view.child(<id>); * var child = view.child(<module>); * * @param {String} name [id|module] * @return {View|undefined} */ child: function(query) { var child = this._lookup[query]; if (child) return child[0] || child; }, module: function(key) { var child; if (!key) return this._module; child = this._lookup[key]; if (child) return child[0] || child; return this.each(function(view) { return view.child(key); }); }, /** * Allows three ways to return * a view's children and direct * children, depending on arguments * passed. * * Example: * * // Return all direct children * view.children(); * * // Return all children that match query. * view.children('orange'); * * @param {undefined|String|Function} query * @return {Array} */ children: function(query) { // If no argument is passd, // return all direct children. if (!query) return this._children; // Get the direct children // that match this query return this._lookup[query] || []; }, modules: function(key) { // Get the direct children // that match this query var list = this._lookup[key] || []; // Then loop each child and run the // same opperation, appending the result // onto the list. this.each(function(view) { list = list.concat(view.children(key)); }); return list; }, /** * Calls the passed function * for each of the view's * children. * * @param {Function} fn [description] * @return {[type]} [description] */ each: function(fn) { var children = this.children(); var l = children.length; var result; for (var i = 0; i < l; i++) { result = fn(children[i]); if (result) return result; } }, toHTML: function() { var data = {}; var html; // Use cache if populated if (this.html) return this.html; // Create an array for view // children data needed in template. data.children = []; // Loop each child this.each(function(child) { html = child.toHTML(); data[child.id()] = html; data.children.push(mixin({ child: html }, child.model.get())); }); // Run the template render method // passing children data (for looping // or child views) mixed with the // view's model data. html = this.template(mixin(data, this.model.get())); // Wrap the html in a FruitMachine // generated root element and return. return this.html = this._wrapHTML(html); }, _wrapHTML: function(html) { return '<' + this.tag + ' class="' + this._module + ' ' + this.classes.join(' ') + '" id="' + this._fmid + '">' + html + '</' + this.tag + '>'; }, purgeHtmlCache: function() { // Clear html this.html = null; // Recurse if (this.parent) this.parent.purgeHtmlCache(); return this; }, render: function() { // Templates the entire view // recursively, returning a // node rather than HTML. var el = this.toNode(); // Sets a new element as a view's // root element (purging descendent // element caches). this.setElement(el); // Handy hook this.trigger('render', { propagate: false }); return this; }, /** * Destroys all children. * * @return {View} */ empty: function() { var children = this.children(); var l = children.length; while (l--) children[l].destroy(); return this; }, setup: function(options) { var shallow = options && options.shallow; // Call 'setup' on all subviews // first (bottom up recursion). if (!shallow) { this.each(function(child) { child.setup(); }); } // Attempt to fetch the view's // root element. Don't continue // if no route element is found. if (!this.getElement()) return this; // If this is already setup, call // `teardown` first so that we don't // duplicate event bindings and shizzle. if (this.isSetup) this.teardown({ shallow: true }); // Fire the `setup` event hook this.trigger('setup', { propagate: false }); // Run onSetup custom function this.onSetup(); // Flag view as 'setup' this.isSetup = true; // For chaining return this; }, 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(); }); } // Don't teardown if this view // hasn't 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) return this; this.trigger('teardown', { propagate: false }); this.onTeardown(); this.isSetup = false; // For chaining return this; }, destroy: function(options) { var children = this._children; var l = 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 View#each() // as the array length gets altered // with each iteration, hense the // reverse while loop. while (l--) { children[l].destroy({ el: false }); } // Don't continue if this view // has already been destroyed. if (this.destroyed) return this; // Detach this view from its // parent and unless otherwise // stated, from the DOM. this.remove(options); // Run teardown so custom // views can bind logic to it this.teardown(options); // Trigger a destroy event // for custom Views to bind to. this.trigger('destroy', { propagate: false }); this.onDestroy(); // Remove the model 'change' event // listener just in case the same // model is being shared with other views. this.model.off('change', this.purgeHtmlCache); // 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._lookup = this._module = this._id = null; }, /** * Removes the View's element * from the DOM. * * @return {FruitMachine} */ remove: function(options) { options = options || {}; var el = this.el; var index; // Unless stated otherwise, // remove the view element // from the its parent node. if (options.el !== false) { if (el && el.parentNode) el.parentNode.removeChild(el); } // If there is no parent view // reference, return here. if (!this.parent) return this; // Remove reference from views array index = this.parent._children.indexOf(this); this.parent._children.splice(index, 1); // Remove references from the lookup this.parent._removeLookup(this); return this; }, /** * Returns the closest root view * element, walking up the chain * until it finds one. * * @return {Element} */ closestElement: function() { var view = this.parent; while (view && !view.el && view.parent) view = view.parent; return view && view.el; }, /** * Returns the View'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} */ getElement: function() { if (!hasDom) return; return this.el = this.el || document.getElementById(this._fmid) || this.parent && util.querySelectorId(this._fmid, this.closestElement()); }, /** * 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 View#getElement is called. * * @param {Element} el * @return {View} */ setElement: function(el) { var existing = this.el; if (existing && existing.parentNode) { existing.parentNode.replaceChild(el, existing); } // Purge all element caches this.purgeElementCaches(); // Update cache this.el = el; return this; }, /** * Recursively purges the * element cache. * * @return void */ purgeElementCaches: function() { this.each(function(child) { child.purgeElementCaches(); }); this.el = null; }, /** * A single method for getting * and setting view data. * * Example: * * // Getters * var all = view.data(); * var one = view.data('myKey'); * * // Setters * view.data('myKey', 'my value'); * view.data({ * myKey: 'my value', * anotherKey: 10 * }); * * @param {String|Object|null} key * @param {*} value * @return {*} */ data: function(key, value) { // If no key and no value have // been passed then return the // entire data store. if (!key && !value) { return this.model.get(); } // If a string key has been // passed, but no value if (typeof key === 'string' && !value) { return this.model.get(key); } // If the user has stated a key // and a value. Set the value on // the key. if (key && value) { this.model.set(key, value); return this; } // If the key is an object literal // then we extend the data store with it. if ('object' === typeof key) { this.model.set(key); return this; } }, /** * Detects whether a view is in * the DOM (useful for debugging). * * @return {Boolean} */ inDOM: function() { if (this.parent) return this.parent.inDOM(); return !!(this.el && this.el.parentNode); }, /** * Templates the whole view and turns * it into a real node. * * @return {Element} */ toNode: function() { var el = document.createElement('div'); el.innerHTML = this.toHTML(); return el.removeChild(el.firstElementChild); }, /** * Empties the destination element * and appends the view into it. * * @param {Element} dest * @return {View} */ inject: function(dest) { if (dest) { dest.innerHTML = ''; this.appendTo(dest); } return this; }, /** * Appends the view element into * the destination element. * * @param {Element} dest * @return {View} */ appendTo: function(dest) { if (this.el && dest && dest.appendChild) { dest.appendChild(this.el); } return this; }, /** * Returns a JSON represention of * a FruitMachine View. This can * be generated serverside and * passed into new FruitMachine(json) * to inflate serverside rendered * views. * * @return {Object} */ 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.data = this.model.get(); return json; } }); /** * Model */ var Model = FruitMachine.Model = function(options) { this.fmid = util.uniqueId('model'); this._data = mixin({}, options); }; // Merge in Events and extend with: mixin(Model.prototype, Events, { get: function(key) { return key ? this._data[key] : this._data; }, set: function(key, value) { var _key; // If a string key is passed // convert it to an object ready // for the next step. if ('string' === typeof key && value) { _key = {}; _key[key] = value; key = _key; } // Merge the object into the data store if ('object' === typeof key) { mixin(this._data, key); this.trigger('change'); for (var prop in key) { this.trigger('change:' + prop, key[prop]); } } return this; }, clear: function() { this._data = {}; return this; }, destroy: function() { this._data = null; }, toJSON: function() { return mixin({}, this._data); } }); /** * Inherit return child; }; // Expose the library if (typeof exports === "object") { module.exports = FruitMachine; <MSG> Moved to normal prototype syntax with some docs and tidying <DFF> @@ -1,3 +1,5 @@ +/*jslint browser:true, node:true*/ + /** * FruitMachine * @@ -27,24 +29,12 @@ * @author Wilson Page <[email protected]> */ -/*jslint browser:true, node:true*/ (function() { 'use strict'; - var FruitMachine = function(options) { - return new View(options); - }; - // Current Version FruitMachine.VERSION = '0.0.1'; - // Global data store - var store = FruitMachine.store = { - modules: {}, - templates: {}, - helpers: {} - }; - // Create local references to some methods var slice = Array.prototype.slice; var has = Object.prototype.hasOwnProperty; @@ -53,21 +43,15 @@ // in the current environment. var hasDom = (typeof document !== 'undefined'); - // Utilities - var util = FruitMachine.util = { + /** + * Util + */ + var util = { bind: function(method, context) { return function() { return method.apply(context, arguments); }; }, - bindAll: function(ob, context) { - for (var key in ob) { - if ('function' === typeof ob[key]) { - ob[key] = util.bind(ob[key], context); - } - } - }, - isArray: function(arg) { return arg instanceof Array; }, @@ -117,12 +101,18 @@ // Alias frequently used utils var mixin = util.mixin; + /** + * Expose `util` + */ + + FruitMachine.util = util; + /** * Events */ var splitter = /\s+/; - var Events = FruitMachine.Events = { + var Events = { // Bind one or more space separated events, `events`, to a `callback` // function. Passing `"all"` will bind the callback to all events fired. @@ -219,131 +209,10 @@ }; /** - * Creates and registers a - * FruitMachine view constructor. - * - * @param {Object|View} - * @return {View} - */ - FruitMachine.module = function(props) { - var module = props.module || 'undefined'; - var View; - - // Remove the module key - delete props.module; - - // If an existing FruitMachine.View - // has been passed in, use that. - // If just an object literal has - // been passed in then we extend the - // default FruitMachine.View prototype - // with the properties passed in. - View = (props.__super__) - ? props - : FruitMachine.View.extend(props); - - // Make sure we explicity set the - // `prototype._module` so that - // `this._module` returns the correct - // module type and not one further - // down the prototype chain. - View.prototype._module = module; - - // Store the module by module type - // so that module can be referred to - // by just a string in layout definitions - return store.modules[module] = View; - }; - - /** - * Removes a module - * from the module store. - * - * If no module key is passed - * the entire store is cleared. - * - * @param {String|undefined} module - * @api public - */ - FruitMachine.module.clear = function(module) { - if (module) delete store.modules[module]; - else store.modules = {}; - }; - - /** - * Helpers - */ - - /** - * Registers a helper - * - * @param {String} name - * @param {Function} helper - * @return void - */ - FruitMachine.helper = function(name, helper) { - store.helpers[name] = helper; - }; - - /** - * Clears one or all - * registered helpers. - * - * @param {String} name - * @api public - */ - FruitMachine.helper.clear = function(name) { - if (name) delete store.helpers[name]; - else store.helpers = {}; - }; - - /** - * Templates - */ - - /** - * Registers templates, or overwrites - * the `getTemplate` method with a - * custom template getter function. - * - * @param {Object|Function} templates - * @return void - */ - FruitMachine.templates = function(templates) { - var type = typeof templates; - if ('object' === type) mixin(store.templates, templates); - else if ('function' === type) FruitMachine.templates.get = templates; - }; - - /** - * The default get template method - * if FruitMachine.template is passed - * a function, this gets overwritten - * by that. - * - * @param {String} module - * @return {Template} + * Expose `Events` */ - var getTemplate = FruitMachine.templates.get = function(module) { - return store.templates[module]; - }; - /** - * Clear reference to a module's - * template, or clear all template - * references and resets the template - * getter method. - * - * @param {String|undefined} module - * @api public - */ - FruitMachine.templates.clear = function(module) { - if (module) delete store.templates[module]; - else { - store.templates = {}; - FruitMachine.templates.get = getTemplate; - } - }; + FruitMachine.Events = Events; /** * View @@ -356,7 +225,7 @@ * @param {Object} options * @api public */ - var View = FruitMachine.View = function(options) { + function View(options) { // Shallow clone the options options = mixin({}, options); @@ -375,7 +244,7 @@ // Run initialize hooks this.onInitialize(options); this.trigger('initialize', [options], { propagate: false }); - }; + } /** * Creates a new FruitMachine view @@ -402,771 +271,806 @@ this.propagate = false; }; - // Extend the prototype - mixin(View.prototype, { + /** + * Configures the new View + * with the options passed + * to the constructor. + * + * @param {Object} options + * @api private + */ + View.prototype._configure = function(options) { + this._id = options.id || util.uniqueId('auto_'); + this._fmid = options.fmid || util.uniqueId('fmid'); + this.tag = options.tag || this.tag || 'div'; + this.classes = this.classes || options.classes || []; + this._module = this._module || options._module; + this.helpers = this.helpers || options.helpers || []; + this.template = this.getTemplate(); + this._lookup = {}; + this._children = []; + + // Use the model passed in, + // or create a model from + // the data passed in. + this.model = options.model || new Model(options.data || {}); + + // Attach helpers + this.helpers.forEach(this.attachHelper, this); + + // Purge html caches when the model is changed + this.purgeHtmlCache = util.bind(this.purgeHtmlCache, this); + this.model.on('change', this.purgeHtmlCache); + }; - /** - * Configures the new View - * with the options passed - * to the constructor. - * - * @param {Object} options - * @api private - */ - _configure: function(options) { - this._id = options.id || util.uniqueId('auto_'); - this._fmid = options.fmid || util.uniqueId('fmid'); - this.tag = options.tag || this.tag || 'div'; - this.classes = this.classes || options.classes || []; - this._module = this._module || options._module; - this.helpers = this.helpers || options.helpers || []; - this.template = this.getTemplate(); - this._lookup = {}; - this._children = []; - - // Use the model passed in, - // or create a model from - // the data passed in. - this.model = options.model || new Model(options.data || {}); - - // Attach helpers - this.helpers.forEach(this.attachHelper, this); - - // Purge html caches when the model is changed - this.purgeHtmlCache = util.bind(this.purgeHtmlCache, this); - this.model.on('change', this.purgeHtmlCache); - }, + // Events + View.prototype.on = Events.on; + View.prototype.off = Events.off; - // Events - on: Events.on, - off: Events.off, + /** + * Proxies the standard Event.trigger + * method so that we can add bubble + * functionality. + * + * Options: + * + * - `propagate` States whether the event + * should bubble through parent views. + * + * @param {String} key + * @param {Array} args + * @param {Object} options + * @return {View} + * @api public + */ + View.prototype.trigger = function(key, args, event) { + var propagate; + + // event can be passed as + // the second or third argument + if (!util.isArray(args)) { + event = args; + args = []; + } - /** - * Proxies the standard Event.trigger - * method so that we can add bubble - * functionality. - * - * Options: - * - * - `propagate` States whether the event - * should bubble through parent views. - * - * @param {String} key - * @param {Array} args - * @param {Object} options - * @return {View} - * @api public - */ - trigger: function(key, args, event) { - var propagate; - - // event can be passed as - // the second or third argument - if (!util.isArray(args)) { - event = args; - args = []; - } + // Use the event object passed + // in, or make a fresh one + event = event || { + target: this, + stopPropagation: stopPropagation + }; - // Use the event object passed - // in, or make a fresh one - event = event || { - target: this, - stopPropagation: stopPropagation - }; + // Trigger event + Events.trigger.apply(this, [key, event].concat(args)); - // Trigger event - Events.trigger.apply(this, [key, event].concat(args)); + // Propagate by default + propagate = (event.propagate !== false); - // Propagate by default - propagate = (event.propagate !== false); + // Trigger the same + // event on the parent view + if (propagate && this.parent) this.parent.trigger(key, args, event); - // Trigger the same - // event on the parent view - if (propagate && this.parent) this.parent.trigger(key, args, event); + // Allow chaining + return this; + }; - // Allow chaining - return this; - }, + View.prototype.attachHelper = function(helper) { + // Allow helpers to be passed in as + // string references to earlier registered + // helpers, or passed in directly as a function. + helper = ('function' === typeof helper) + ? helper + : store.helpers[helper]; + + // Run the helper function + if (helper) helper(this, FruitMachine); + }, + + View.prototype.getTemplate = function() { + // Use the template defined on the + // custom view, or use the template getter. + var template = this.template || FruitMachine.templates.get(this._module); + + // Warn if no template found + if (!template) return console.warn('FM - No template for %s', this._module); + + // Accomodate for template.render() or template() + // this.template.render has to be bound to stop + // a hogan.js error if the context is wrong. + return template.render + ? util.bind(template.render, template) + : template; + }; - // Empty methods you can overwrite - // in your custom view logic. - onInitialize: function() {}, - onSetup: function() {}, - onTeardown: function() {}, - onDestroy: function() {}, - - attachHelper: function(helper) { - // Allow helpers to be passed in as - // string references to earlier registered - // helpers, or passed in directly as a function. - helper = ('function' === typeof helper) - ? helper - : store.helpers[helper]; - - // Run the helper function - if (helper) helper(this, FruitMachine); - }, + View.prototype.add = function(children, options) { + var at = options && options.at; + var inject = options && options.inject; + var child; - getTemplate: function() { - // Use the template defined on the - // custom view, or use the template getter. - var template = this.template || FruitMachine.templates.get(this._module); + if (!children) return; - // Warn if no template found - if (!template) return console.warn('FM - No template for %s', this._module); + // Make sure it's an array + children = [].concat(children); - // Accomodate for template.render() or template() - // this.template.render has to be bound to stop - // a hogan.js error if the context is wrong. - return template.render - ? util.bind(template.render, template) - : template; - }, + for (var i = 0, l = children.length; i < l; i++) { + child = children[i]; + if (!(child instanceof View)) child = new View(child); - add: function(children, options) { - var at = options && options.at; - var inject = options && options.inject; - var child; + util.insert(child, this._children, at); + this._addLookup(child); + child.parent = this; - if (!children) return; + // 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.injectElement(child.el, options); + } - // Make sure it's an array - children = [].concat(children); + this.purgeHtmlCache(); - for (var i = 0, l = children.length; i < l; i++) { - child = children[i]; - if (!(child instanceof View)) child = new View(child); + return this; + }; - util.insert(child, this._children, at); - this._addLookup(child); - child.parent = this; + View.prototype._addLookup = function(child) { + this._lookup[child.id()] = child; + this._lookup[child._module] = this._lookup[child._module] || []; + this._lookup[child._module].push(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.injectElement(child.el, options); - } + View.prototype._removeLookup = function(child) { + var index = this._lookup[child._module].indexOf(child); + this._lookup[child._module].splice(index, 1); + delete this._lookup[child._id]; + }; - this.purgeHtmlCache(); + View.prototype.injectElement = function(el, options) { + var at = options && options.at; + var parent = this.el; + if (!el || !parent) return; - return this; - }, + if (typeof at !== 'undefined') { + parent.insertBefore(el, parent.children[at]); + } else { + parent.appendChild(el); + } + }; - _addLookup: function(child) { - this._lookup[child.id()] = child; - this._lookup[child._module] = this._lookup[child._module] || []; - this._lookup[child._module].push(child); - }, + /** + * Returns a decendent module + * by id, or if called with no + * arguments, returns this view's id. + * + * @param {String|undefined} id + * @return {View|String} + * @api public + */ + View.prototype.id = function(id) { + return id + ? this.module(id) + : this._id; + }; - _removeLookup: function(child) { - var index = this._lookup[child._module].indexOf(child); - this._lookup[child._module].splice(index, 1); - delete this._lookup[child._id]; - }, + /** + * Returns the first child + * view that matches the query. + * + * Example: + * + * var child = view.child(<id>); + * var child = view.child(<module>); + * + * @param {String} name [id|module] + * @return {View|undefined} + */ + View.prototype.child = function(query) { + var child = this._lookup[query]; + if (child) return child[0] || child; + }; - injectElement: function(el, options) { - var at = options && options.at; - var parent = this.el; - if (!el || !parent) return; + View.prototype.module = function(key) { + var child; - if (typeof at !== 'undefined') { - parent.insertBefore(el, parent.children[at]); - } else { - parent.appendChild(el); - } - }, + if (!key) return this._module; - /** - * Returns a decendent module - * by id, or if called with no - * arguments, returns this view's id. - * - * @param {String|undefined} id - * @return {View|String} - * @api public - */ - id: function(id) { - return id - ? this.module(id) - : this._id; - }, + child = this._lookup[key]; + if (child) return child[0] || child; - /** - * Returns the first child - * view that matches the query. - * - * Example: - * - * var child = view.child(<id>); - * var child = view.child(<module>); - * - * @param {String} name [id|module] - * @return {View|undefined} - */ - child: function(query) { - var child = this._lookup[query]; - if (child) return child[0] || child; - }, + return this.each(function(view) { + return view.child(key); + }); + }; - module: function(key) { - var child; + /** + * Allows three ways to return + * a view's children and direct + * children, depending on arguments + * passed. + * + * Example: + * + * // Return all direct children + * view.children(); + * + * // Return all children that match query. + * view.children('orange'); + * + * @param {undefined|String|Function} query + * @return {Array} + */ + View.prototype.children = function(query) { - if (!key) return this._module; + // If no argument is passd, + // return all direct children. + if (!query) return this._children; - child = this._lookup[key]; - if (child) return child[0] || child; + // Get the direct children + // that match this query + return this._lookup[query] || []; + }; - return this.each(function(view) { - return view.child(key); - }); - }, + View.prototype.modules = function(key) { - /** - * Allows three ways to return - * a view's children and direct - * children, depending on arguments - * passed. - * - * Example: - * - * // Return all direct children - * view.children(); - * - * // Return all children that match query. - * view.children('orange'); - * - * @param {undefined|String|Function} query - * @return {Array} - */ - children: function(query) { + // Get the direct children + // that match this query + var list = this._lookup[key] || []; - // If no argument is passd, - // return all direct children. - if (!query) return this._children; + // Then loop each child and run the + // same opperation, appending the result + // onto the list. + this.each(function(view) { + list = list.concat(view.children(key)); + }); - // Get the direct children - // that match this query - return this._lookup[query] || []; - }, + return list; + }; - modules: function(key) { + /** + * Calls the passed function + * for each of the view's + * children. + * + * @param {Function} fn + * @return {[type]} + */ + View.prototype.each = function(fn) { + var children = this.children(); + var l = children.length; + var result; + + for (var i = 0; i < l; i++) { + result = fn(children[i]); + if (result) return result; + } + }; - // Get the direct children - // that match this query - var list = this._lookup[key] || []; + View.prototype.toHTML = function() { + var data = {}; + var html; + + // Use cache if populated + if (this.html) return this.html; + + // Create an array for view + // children data needed in template. + data.children = []; + + // Loop each child + this.each(function(child) { + html = child.toHTML(); + data[child.id()] = html; + data.children.push(mixin({ child: html }, child.model.get())); + }); + + // Run the template render method + // passing children data (for looping + // or child views) mixed with the + // view's model data. + html = this.template(mixin(data, this.model.get())); + + // Wrap the html in a FruitMachine + // generated root element and return. + return this.html = this._wrapHTML(html); + }; - // Then loop each child and run the - // same opperation, appending the result - // onto the list. - this.each(function(view) { - list = list.concat(view.children(key)); - }); + /** + * Wraps the module html in + * a root element. + * + * @param {String} html + * @return {String} + * @api private + */ + View.prototype._wrapHTML = function(html) { + return '<' + this.tag + ' class="' + this._module + ' ' + this.classes.join(' ') + '" id="' + this._fmid + '">' + html + '</' + this.tag + '>'; + }; - return list; - }, + /** + * Clears the html cache + * propagating up the + * anchestor chain + * + * @return {View} + * @api private + */ + View.prototype.purgeHtmlCache = function() { - /** - * Calls the passed function - * for each of the view's - * children. - * - * @param {Function} fn [description] - * @return {[type]} [description] - */ - each: function(fn) { - var children = this.children(); - var l = children.length; - var result; - - for (var i = 0; i < l; i++) { - result = fn(children[i]); - if (result) return result; - } - }, + // Clear html + this.html = null; - toHTML: function() { - var data = {}; - var html; + // Recurse + if (this.parent) this.parent.purgeHtmlCache(); - // Use cache if populated - if (this.html) return this.html; + return this; + }; - // Create an array for view - // children data needed in template. - data.children = []; + View.prototype.render = function() { - // Loop each child - this.each(function(child) { - html = child.toHTML(); - data[child.id()] = html; - data.children.push(mixin({ child: html }, child.model.get())); - }); - - // Run the template render method - // passing children data (for looping - // or child views) mixed with the - // view's model data. - html = this.template(mixin(data, this.model.get())); - - // Wrap the html in a FruitMachine - // generated root element and return. - return this.html = this._wrapHTML(html); - }, + // Templates the entire view + // recursively, returning a + // node rather than HTML. + var el = this.toNode(); - _wrapHTML: function(html) { - return '<' + this.tag + ' class="' + this._module + ' ' + this.classes.join(' ') + '" id="' + this._fmid + '">' + html + '</' + this.tag + '>'; - }, + // Sets a new element as a view's + // root element (purging descendent + // element caches). + this.setElement(el); - purgeHtmlCache: function() { + // Handy hook + this.trigger('render', { propagate: false }); - // Clear html - this.html = null; + return this; + }; - // Recurse - if (this.parent) this.parent.purgeHtmlCache(); + View.prototype.setup = function(options) { + var shallow = options && options.shallow; - return this; - }, + // Call 'setup' on all subviews + // first (bottom up recursion). + if (!shallow) { + this.each(function(child) { + child.setup(); + }); + } - render: function() { + // Attempt to fetch the view's + // root element. Don't continue + // if no route element is found. + if (!this.getElement()) return this; - // Templates the entire view - // recursively, returning a - // node rather than HTML. - var el = this.toNode(); + // 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 }); - // Sets a new element as a view's - // root element (purging descendent - // element caches). - this.setElement(el); + // Fire the `setup` event hook + this.trigger('setup', { propagate: false }); - // Handy hook - this.trigger('render', { propagate: false }); + // Run onSetup custom function + this.onSetup(); - return this; - }, + // Flag view as 'setup' + this.isSetup = true; - /** - * Destroys all children. - * - * @return {View} - */ - empty: function() { - var children = this.children(); - var l = children.length; + // For chaining + return this; + }; - while (l--) children[l].destroy(); + View.prototype.teardown = function(options) { + var shallow = options && options.shallow; - return this; - }, + // Call 'setup' on all subviews + // first (bottom up recursion). + if (!shallow) { + this.each(function(child) { + child.teardown(); + }); + } - setup: function(options) { - var shallow = options && options.shallow; + // Don't teardown if this view + // hasn't 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) return this; - // Call 'setup' on all subviews - // first (bottom up recursion). - if (!shallow) { - this.each(function(child) { - child.setup(); - }); - } + this.trigger('teardown', { propagate: false }); + this.onTeardown(); + this.isSetup = false; - // Attempt to fetch the view's - // root element. Don't continue - // if no route element is found. - if (!this.getElement()) return this; + // For chaining + 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 }); + View.prototype.destroy = function(options) { + var children = this._children; + var l = 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 View#each() + // as the array length gets altered + // with each iteration, hense the + // reverse while loop. + while (l--) { + children[l].destroy({ el: false }); + } - // Fire the `setup` event hook - this.trigger('setup', { propagate: false }); + // Don't continue if this view + // has already been destroyed. + if (this.destroyed) return this; + + // Detach this view from its + // parent and unless otherwise + // stated, from the DOM. + this.remove(options); + + // Run teardown so custom + // views can bind logic to it + this.teardown(options); + + // Trigger a destroy event + // for custom Views to bind to. + this.trigger('destroy', { propagate: false }); + this.onDestroy(); + + // Remove the model 'change' event + // listener just in case the same + // model is being shared with other views. + this.model.off('change', this.purgeHtmlCache); + + // 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._lookup = this._module = this._id = null; + }; - // Run onSetup custom function - this.onSetup(); + // Empty methods you can overwrite + // in your custom view logic. + View.prototype.onInitialize = function() {}; + View.prototype.onSetup = function() {}; + View.prototype.onTeardown = function() {}; + View.prototype.onDestroy = function() {}; - // Flag view as 'setup' - this.isSetup = true; + /** + * Removes the View's element + * from the DOM. + * + * @return {FruitMachine} + */ + View.prototype.remove = function(options) { + options = options || {}; + var el = this.el; + var index; + + // Unless stated otherwise, + // remove the view element + // from the its parent node. + if (options.el !== false) { + if (el && el.parentNode) el.parentNode.removeChild(el); + } - // For chaining - return this; - }, + // If there is no parent view + // reference, return here. + if (!this.parent) return this; - teardown: function(options) { - var shallow = options && options.shallow; + // Remove reference from views array + index = this.parent._children.indexOf(this); + this.parent._children.splice(index, 1); - // Call 'setup' on all subviews - // first (bottom up recursion). - if (!shallow) { - this.each(function(child) { - child.teardown(); - }); - } + // Remove references from the lookup + this.parent._removeLookup(this); - // Don't teardown if this view - // hasn't 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) return this; + return this; + }; - this.trigger('teardown', { propagate: false }); - this.onTeardown(); - this.isSetup = false; + /** + * Destroys all children. + * + * @return {View} + */ + View.prototype.empty = function() { + var children = this.children(); + var l = children.length; - // For chaining - return this; - }, + while (l--) children[l].destroy(); - destroy: function(options) { - var children = this._children; - var l = 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 View#each() - // as the array length gets altered - // with each iteration, hense the - // reverse while loop. - while (l--) { - children[l].destroy({ el: false }); - } + return this; + }; - // Don't continue if this view - // has already been destroyed. - if (this.destroyed) return this; - - // Detach this view from its - // parent and unless otherwise - // stated, from the DOM. - this.remove(options); - - // Run teardown so custom - // views can bind logic to it - this.teardown(options); - - // Trigger a destroy event - // for custom Views to bind to. - this.trigger('destroy', { propagate: false }); - this.onDestroy(); - - // Remove the model 'change' event - // listener just in case the same - // model is being shared with other views. - this.model.off('change', this.purgeHtmlCache); - - // 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._lookup = this._module = this._id = null; - }, + /** + * Returns the closest root view + * element, walking up the chain + * until it finds one. + * + * @return {Element} + */ + View.prototype.closestElement = function() { + var view = this.parent; + while (view && !view.el && view.parent) view = view.parent; + return view && view.el; + }; - /** - * Removes the View's element - * from the DOM. - * - * @return {FruitMachine} - */ - remove: function(options) { - options = options || {}; - var el = this.el; - var index; - - // Unless stated otherwise, - // remove the view element - // from the its parent node. - if (options.el !== false) { - if (el && el.parentNode) el.parentNode.removeChild(el); - } + /** + * Returns the View'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} + */ + View.prototype.getElement = function() { + if (!hasDom) return; + return this.el = this.el + || document.getElementById(this._fmid) + || this.parent && util.querySelectorId(this._fmid, this.closestElement()); + }; - // If there is no parent view - // reference, return here. - if (!this.parent) return this; + /** + * 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 | 865 | Moved to normal prototype syntax with some docs and tidying | 803 | .js | js | mit | ftlabs/fruitmachine |
10067906 | <NME> tests.js
<BEF> /**
* loadjs tests
* @module test/tests.js
*/
var pathsLoaded = null, // file register
testEl = null,
assert = chai.assert,
expect = chai.expect;
describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
// reset loadjs dependencies
loadjs.reset();
});
// ==========================================================================
// JavaScript file loading tests
// ==========================================================================
describe('JavaScript file loading tests', function() {
it('should call success callback on valid path', function(done) {
loadjs(['assets/file1.js'], {
success: function() {
throw "Executed success callback";
},
function(pathsNotFound) {
// TODO: implement and test pathsNotFound
done();
});
});
loadjs(['assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle1');
success: function() {
assert.equal(scriptTags[0].path, 'assets/file1.js');
assert.equal(scriptTags[1].path, 'assets/file2.js');
assert.equal(scriptTags[0].el.crossOrigin, undefined);
assert.equal(scriptTags[1].el.crossOrigin, 'anonymous');
done();
}
});
});
it('should bypass insertion if before returns `false`', function(done) {
loadjs(['assets/file1.js'], {
before: function(path, el) {
// append to body (instead of head)
document.body.appendChild(el);
// return `false` to bypass default DOM insertion
return false;
},
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
// verify that file was added to body
var els = document.body.querySelectorAll('script'),
el;
for (var i=0; i < els.length; i++) {
el = els[i];
if (el.src.indexOf('assets/file1.js') !== -1) done();
}
}
});
});
it('should call success callback on two valid paths', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should support async false', function(done) {
this.timeout(5000);
var numCompleted = 0,
numTests = 20,
paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js'];
// run tests sequentially
var testFn = function(paths) {
// add cache busters
var pathsUncached = paths.slice(0);
pathsUncached[0] += '?_=' + Math.random();
pathsUncached[1] += '?_=' + Math.random();
loadjs(pathsUncached, {
success: function() {
var f1 = paths[0].replace('assets/', '');
var f2 = paths[1].replace('assets/', '');
// check load order
assert.isTrue(pathsLoaded[f1]);
assert.isFalse(pathsLoaded[f2]);
// increment tests
numCompleted += 1;
if (numCompleted === numTests) {
// exit
done();
} else {
// reset register
pathsLoaded = {};
// run test again
paths.reverse();
testFn(paths);
}
},
async: false
});
};
// run tests
testFn(paths);
});
it('should support multiple tries', function(done) {
loadjs('assets/file-numretries.js', {
error: function() {
// check number of scripts in document
var selector = 'script[src="assets/file-numretries.js"]',
scripts = document.querySelectorAll(selector);
if (scripts.length === 2) done();
},
numRetries: 1
});
});
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
// custom filter under Options
//
xit('it should report ad blocked scripts as missing', function(done) {
var s1 = 'https://www.googletagservices.com/tag/js/gpt.js',
s2 = 'https://munchkin.marketo.net/munchkin-beta.js';
loadjs([s1, s2, 'assets/file1.js'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 2);
assert.equal(pathsNotFound[0], s1);
assert.equal(pathsNotFound[1], s2);
done();
}
});
});
});
// ==========================================================================
// CSS file loading tests
// ==========================================================================
describe('CSS file loading tests', function() {
before(function() {
// add test div to body for css tests
testEl = document.createElement('div');
testEl.className = 'test-div mui-container';
testEl.style.display = 'inline-block';
document.body.appendChild(testEl);
});
afterEach(function() {
var els = document.getElementsByTagName('link'),
i = els.length,
el;
// iteratete through stylesheets
while (i--) {
el = els[i];
// remove test stylesheets
if (el.href.indexOf('mocha.css') === -1) {
el.parentNode.removeChild(el);
}
}
});
it('should load one file', function(done) {
loadjs(['assets/file1.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/file1.css', 'assets/file2.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 200);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
done();
}
});
});
it('should support mix of css and js', function(done) {
loadjs(['assets/file1.css', 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should support forced "css!" files', function(done) {
loadjs(['css!assets/file1.css'], {
success: function() {
// loop through files
var els = document.getElementsByTagName('link'),
i = els.length,
el;
while (i--) {
if (els[i].href.indexOf('file1.css') !== -1) done();
}
}
});
});
it('supports urls with query arguments', function(done) {
loadjs(['assets/file1.css?x=x'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
loadjs(['assets/file1.css#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
loadjs(['assets/file1.css?x=x#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load external css files', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], {
success: function() {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '15px');
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
done();
}
});
});
// teardown
return after(function() {
// remove test div
testEl.parentNode.removeChild(testEl);
});
});
// ==========================================================================
// Image file loading tests
// ==========================================================================
describe('Image file loading tests', function() {
function assertLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// verify image was loaded
if (img.src === src) assert.equal(img.naturalWidth > 0, true);
});
}
function assertNotLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// fail if image was loaded
if (img.src === src) assert.equal(img.naturalWidth, 0);
});
}
it('should load one file', function(done) {
loadjs(['assets/flash.png'], {
success: function() {
assertLoaded('assets/flash.png');
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/flash.png', 'assets/flash.jpg'], {
success: function() {
assertLoaded('assets/flash.png');
assertLoaded('assets/flash.jpg');
done();
}
});
});
it('detects png|gif|jpg|svg|webp extensions', function(done) {
let files = [
'assets/flash.png',
'assets/flash.gif',
'assets/flash.jpg',
'assets/flash.svg',
'assets/flash.webp'
];
loadjs(files, function() {
files.forEach(file => {assertLoaded(file);});
done();
});
});
it('supports urls with query arguments', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
var src = 'assets/flash.png#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
var src = 'assets/flash.png';
src += '?' + Math.random();
src += '#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should support forced "img!" files', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
var src1 = 'assets/flash.png?' + Math.random(),
src2 = 'assets/flash-doesntexist.png?' + Math.random();
loadjs(['img!' + src1, 'img!' + src2], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assertLoaded(src1);
assertNotLoaded(src2);
done();
}
});
});
it('should support mix of img and js', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src, 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assertLoaded(src);
done();
}
});
});
it('should load external img files', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/mui-logo.png?';
src += Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/';
src += 'mui-logo-doesntexist.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assertNotLoaded(src);
done();
}
});
});
});
// ==========================================================================
// API tests
// ==========================================================================
describe('API tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle');
};
expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should chain loadjs object', function(done) {
function bothDone() {
if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done();
}
// define bundles
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs
.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
}
});
});
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file-doesntexist.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
});
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
// execute done
loadjs.done('plugin');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
loadjs.done('plugin');
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
}, 1000);
});
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
// use 1 second delay
setTimeout(function() {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
}, 1000);
});
it('should reset dependencies statuses', function() {
loadjs(['assets/file1.js'], 'cleared');
loadjs.reset();
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'cleared');
};
expect(fn).not.to.throw("LoadJS");
});
it('should indicate if bundle has already been defined', function() {
loadjs(['assets/file1/js'], 'bundle1');
assert.equal(loadjs.isDefined('bundle1'), true);
assert.equal(loadjs.isDefined('bundleXX'), false);
});
it('should accept success callback functions to loadjs()', function(done) {
loadjs('assets/file1.js', function() {
done();
});
});
it('should accept success callback functions to .ready()', function(done) {
loadjs.done('plugin');
loadjs.ready('plugin', function() {
done();
});
});
it('should return Promise object if returnPromise is true', function() {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
// verify that response object is a Promise
assert.equal(prom instanceof Promise, true);
});
it('Promise object should support resolutions', function(done) {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
prom.then(function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('Promise object should support rejections', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom.then(
function(){},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
);
});
it('Promise object should support catches', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom
.catch(function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('supports Promises and success callbacks', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
var prom = loadjs('assets/file1.js', {
success: completedFn,
returnPromise: true
});
prom.then(completedFn);
});
it('supports Promises and bundle ready events', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
.then(completedFn);
loadjs.ready('bundle1', completedFn);
});
});
});
<MSG> backup
<DFF> @@ -31,7 +31,8 @@ describe('loadjs tests', function() {
throw "Executed success callback";
},
function(pathsNotFound) {
- // TODO: implement and test pathsNotFound
+ assert.equal(pathsNotFound.length, 1);
+ //assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
@@ -46,6 +47,20 @@ describe('loadjs tests', function() {
});
+ it('should call fail callback on one invalid path', function(done) {
+ loadjs(['assets/file1.js', 'assets/file-doesntexist.js'],
+ function() {
+ throw "Executed success callback";
+ },
+ function(pathsNotFound) {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsNotFound.length, 1);
+ //assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
+ done();
+ });
+ });
+
+
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle1');
| 16 | backup | 1 | .js | js | mit | muicss/loadjs |
10067907 | <NME> tests.js
<BEF> /**
* loadjs tests
* @module test/tests.js
*/
var pathsLoaded = null, // file register
testEl = null,
assert = chai.assert,
expect = chai.expect;
describe('LoadJS tests', function() {
beforeEach(function() {
// reset register
pathsLoaded = {};
// reset loadjs dependencies
loadjs.reset();
});
// ==========================================================================
// JavaScript file loading tests
// ==========================================================================
describe('JavaScript file loading tests', function() {
it('should call success callback on valid path', function(done) {
loadjs(['assets/file1.js'], {
success: function() {
throw "Executed success callback";
},
function(pathsNotFound) {
// TODO: implement and test pathsNotFound
done();
});
});
loadjs(['assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle1');
success: function() {
assert.equal(scriptTags[0].path, 'assets/file1.js');
assert.equal(scriptTags[1].path, 'assets/file2.js');
assert.equal(scriptTags[0].el.crossOrigin, undefined);
assert.equal(scriptTags[1].el.crossOrigin, 'anonymous');
done();
}
});
});
it('should bypass insertion if before returns `false`', function(done) {
loadjs(['assets/file1.js'], {
before: function(path, el) {
// append to body (instead of head)
document.body.appendChild(el);
// return `false` to bypass default DOM insertion
return false;
},
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
// verify that file was added to body
var els = document.body.querySelectorAll('script'),
el;
for (var i=0; i < els.length; i++) {
el = els[i];
if (el.src.indexOf('assets/file1.js') !== -1) done();
}
}
});
});
it('should call success callback on two valid paths', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.js', 'assets/file-doesntexist.js'], {
success: function() {
throw "Executed success callback";
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
});
});
it('should support async false', function(done) {
this.timeout(5000);
var numCompleted = 0,
numTests = 20,
paths = ['assets/asyncfalse1.js', 'assets/asyncfalse2.js'];
// run tests sequentially
var testFn = function(paths) {
// add cache busters
var pathsUncached = paths.slice(0);
pathsUncached[0] += '?_=' + Math.random();
pathsUncached[1] += '?_=' + Math.random();
loadjs(pathsUncached, {
success: function() {
var f1 = paths[0].replace('assets/', '');
var f2 = paths[1].replace('assets/', '');
// check load order
assert.isTrue(pathsLoaded[f1]);
assert.isFalse(pathsLoaded[f2]);
// increment tests
numCompleted += 1;
if (numCompleted === numTests) {
// exit
done();
} else {
// reset register
pathsLoaded = {};
// run test again
paths.reverse();
testFn(paths);
}
},
async: false
});
};
// run tests
testFn(paths);
});
it('should support multiple tries', function(done) {
loadjs('assets/file-numretries.js', {
error: function() {
// check number of scripts in document
var selector = 'script[src="assets/file-numretries.js"]',
scripts = document.querySelectorAll(selector);
if (scripts.length === 2) done();
},
numRetries: 1
});
});
// Un-'x' this for testing ad blocked scripts.
// Ghostery: Disallow "Google Adservices"
// AdBlock Plus: Add "www.googletagservices.com/tag/js/gpt.js" as a
// custom filter under Options
//
xit('it should report ad blocked scripts as missing', function(done) {
var s1 = 'https://www.googletagservices.com/tag/js/gpt.js',
s2 = 'https://munchkin.marketo.net/munchkin-beta.js';
loadjs([s1, s2, 'assets/file1.js'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsNotFound.length, 2);
assert.equal(pathsNotFound[0], s1);
assert.equal(pathsNotFound[1], s2);
done();
}
});
});
});
// ==========================================================================
// CSS file loading tests
// ==========================================================================
describe('CSS file loading tests', function() {
before(function() {
// add test div to body for css tests
testEl = document.createElement('div');
testEl.className = 'test-div mui-container';
testEl.style.display = 'inline-block';
document.body.appendChild(testEl);
});
afterEach(function() {
var els = document.getElementsByTagName('link'),
i = els.length,
el;
// iteratete through stylesheets
while (i--) {
el = els[i];
// remove test stylesheets
if (el.href.indexOf('mocha.css') === -1) {
el.parentNode.removeChild(el);
}
}
});
it('should load one file', function(done) {
loadjs(['assets/file1.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/file1.css', 'assets/file2.css'], {
success: function() {
assert.equal(testEl.offsetWidth, 200);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
loadjs(['assets/file1.css', 'assets/file-doesntexist.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(testEl.offsetWidth, 100);
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.css');
done();
}
});
});
it('should support mix of css and js', function(done) {
loadjs(['assets/file1.css', 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should support forced "css!" files', function(done) {
loadjs(['css!assets/file1.css'], {
success: function() {
// loop through files
var els = document.getElementsByTagName('link'),
i = els.length,
el;
while (i--) {
if (els[i].href.indexOf('file1.css') !== -1) done();
}
}
});
});
it('supports urls with query arguments', function(done) {
loadjs(['assets/file1.css?x=x'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
loadjs(['assets/file1.css#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
loadjs(['assets/file1.css?x=x#anchortag'], {
success: function() {
assert.equal(testEl.offsetWidth, 100);
done();
}
});
});
it('should load external css files', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui.min.css'], {
success: function() {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '15px');
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
loadjs(['//cdn.muicss.com/mui-0.6.8/css/mui-doesnotexist.min.css'], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
var styleObj = getComputedStyle(testEl);
assert.equal(styleObj.getPropertyValue('padding-left'), '0px');
assert.equal(pathsNotFound.length, 1);
done();
}
});
});
// teardown
return after(function() {
// remove test div
testEl.parentNode.removeChild(testEl);
});
});
// ==========================================================================
// Image file loading tests
// ==========================================================================
describe('Image file loading tests', function() {
function assertLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// verify image was loaded
if (img.src === src) assert.equal(img.naturalWidth > 0, true);
});
}
function assertNotLoaded(src) {
// loop through images
var imgs = document.getElementsByTagName('img');
Array.prototype.slice.call(imgs).forEach(function(img) {
// fail if image was loaded
if (img.src === src) assert.equal(img.naturalWidth, 0);
});
}
it('should load one file', function(done) {
loadjs(['assets/flash.png'], {
success: function() {
assertLoaded('assets/flash.png');
done();
}
});
});
it('should load multiple files', function(done) {
loadjs(['assets/flash.png', 'assets/flash.jpg'], {
success: function() {
assertLoaded('assets/flash.png');
assertLoaded('assets/flash.jpg');
done();
}
});
});
it('detects png|gif|jpg|svg|webp extensions', function(done) {
let files = [
'assets/flash.png',
'assets/flash.gif',
'assets/flash.jpg',
'assets/flash.svg',
'assets/flash.webp'
];
loadjs(files, function() {
files.forEach(file => {assertLoaded(file);});
done();
});
});
it('supports urls with query arguments', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with anchor tags', function(done) {
var src = 'assets/flash.png#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('supports urls with query arguments and anchor tags', function(done) {
var src = 'assets/flash.png';
src += '?' + Math.random();
src += '#' + Math.random();
loadjs([src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should support forced "img!" files', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error callback on one invalid path', function(done) {
var src1 = 'assets/flash.png?' + Math.random(),
src2 = 'assets/flash-doesntexist.png?' + Math.random();
loadjs(['img!' + src1, 'img!' + src2], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assertLoaded(src1);
assertNotLoaded(src2);
done();
}
});
});
it('should support mix of img and js', function(done) {
var src = 'assets/flash.png?' + Math.random();
loadjs(['img!' + src, 'assets/file1.js'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assertLoaded(src);
done();
}
});
});
it('should load external img files', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/mui-logo.png?';
src += Math.random();
loadjs(['img!' + src], {
success: function() {
assertLoaded(src);
done();
}
});
});
it('should call error on missing external file', function(done) {
this.timeout(0);
var src = 'https://www.muicss.com/static/images/';
src += 'mui-logo-doesntexist.png?' + Math.random();
loadjs(['img!' + src], {
success: function() {
throw new Error('Executed success callback');
},
error: function(pathsNotFound) {
assertNotLoaded(src);
done();
}
});
});
});
// ==========================================================================
// API tests
// ==========================================================================
describe('API tests', function() {
it('should throw an error if bundle is already defined', function() {
// define bundle
loadjs(['assets/file1.js'], 'bundle');
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'bundle');
};
expect(fn).to.throw("LoadJS");
});
it('should create a bundle id and a callback inline', function(done) {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should chain loadjs object', function(done) {
function bothDone() {
if (pathsLoaded['file1.js'] && pathsLoaded['file2.js']) done();
}
// define bundles
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs
.ready('bundle1', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
bothDone();
}})
.ready('bundle2', {
success: function() {
assert.equal(pathsLoaded['file2.js'], true);
bothDone();
}
});
});
it('should handle multiple dependencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file2.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
});
it('should error on missing depdendencies', function(done) {
loadjs('assets/file1.js', 'bundle1');
loadjs('assets/file-doesntexist.js', 'bundle2');
loadjs.ready(['bundle1', 'bundle2'], {
success: function() {
throw "Executed success callback";
},
error: function(depsNotFound) {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(depsNotFound.length, 1);
assert.equal(depsNotFound[0], 'bundle2');
done();
}
});
});
it('should execute callbacks on .done()', function(done) {
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
// execute done
loadjs.done('plugin');
});
it('should execute callbacks created after .done()', function(done) {
// execute done
loadjs.done('plugin');
// add handler
loadjs.ready('plugin', {
success: function() {
done();
}
});
});
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
// use 1 second delay to let files load
setTimeout(function() {
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
}, 1000);
});
it('should allow bundle callbacks before definitions', function(done) {
// define callback
loadjs.ready('bundle', {
success: function() {
assert.equal(pathsLoaded['file1.js'], true);
assert.equal(pathsLoaded['file2.js'], true);
done();
}
});
// use 1 second delay
setTimeout(function() {
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle');
}, 1000);
});
it('should reset dependencies statuses', function() {
loadjs(['assets/file1.js'], 'cleared');
loadjs.reset();
// define bundle again
var fn = function() {
loadjs(['assets/file1.js'], 'cleared');
};
expect(fn).not.to.throw("LoadJS");
});
it('should indicate if bundle has already been defined', function() {
loadjs(['assets/file1/js'], 'bundle1');
assert.equal(loadjs.isDefined('bundle1'), true);
assert.equal(loadjs.isDefined('bundleXX'), false);
});
it('should accept success callback functions to loadjs()', function(done) {
loadjs('assets/file1.js', function() {
done();
});
});
it('should accept success callback functions to .ready()', function(done) {
loadjs.done('plugin');
loadjs.ready('plugin', function() {
done();
});
});
it('should return Promise object if returnPromise is true', function() {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
// verify that response object is a Promise
assert.equal(prom instanceof Promise, true);
});
it('Promise object should support resolutions', function(done) {
var prom = loadjs(['assets/file1.js'], {returnPromise: true});
prom.then(function() {
assert.equal(pathsLoaded['file1.js'], true);
done();
});
});
it('Promise object should support rejections', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom.then(
function(){},
function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
}
);
});
it('Promise object should support catches', function(done) {
var prom = loadjs(['assets/file-doesntexist.js'], {returnPromise: true});
prom
.catch(function(pathsNotFound) {
assert.equal(pathsNotFound.length, 1);
assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
it('supports Promises and success callbacks', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
var prom = loadjs('assets/file1.js', {
success: completedFn,
returnPromise: true
});
prom.then(completedFn);
});
it('supports Promises and bundle ready events', function(done) {
var numCompleted = 0;
function completedFn() {
numCompleted += 1;
if (numCompleted === 2) done();
};
loadjs('assets/file1.js', 'bundle1', {returnPromise: true})
.then(completedFn);
loadjs.ready('bundle1', completedFn);
});
});
});
<MSG> backup
<DFF> @@ -31,7 +31,8 @@ describe('loadjs tests', function() {
throw "Executed success callback";
},
function(pathsNotFound) {
- // TODO: implement and test pathsNotFound
+ assert.equal(pathsNotFound.length, 1);
+ //assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
done();
});
});
@@ -46,6 +47,20 @@ describe('loadjs tests', function() {
});
+ it('should call fail callback on one invalid path', function(done) {
+ loadjs(['assets/file1.js', 'assets/file-doesntexist.js'],
+ function() {
+ throw "Executed success callback";
+ },
+ function(pathsNotFound) {
+ assert.equal(pathsLoaded['file1.js'], true);
+ assert.equal(pathsNotFound.length, 1);
+ //assert.equal(pathsNotFound[0], 'assets/file-doesntexist.js');
+ done();
+ });
+ });
+
+
it('should define bundles', function(done) {
// define bundle
loadjs(['assets/file1.js', 'assets/file2.js'], 'bundle1');
| 16 | backup | 1 | .js | js | mit | muicss/loadjs |
10067908 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067909 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067910 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067911 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067912 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067913 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067914 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067915 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067916 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067917 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067918 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067919 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067920 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067921 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067922 | <NME> AvaloniaEdit.csproj
<BEF> <Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsNotAsErrors>0612,0618</WarningsNotAsErrors>
<PackageId>Avalonia.AvaloniaEdit</PackageId>
</PropertyGroup>
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
<None Remove="Search\Assets\CaseSensitive.png" />
<None Remove="Search\Assets\CompleteWord.png" />
<None Remove="Search\Assets\FindNext.png" />
<None Remove="Search\Assets\FindPrevious.png" />
<None Remove="Search\Assets\RegularExpression.png" />
<None Remove="Search\Assets\ReplaceAll.png" />
<None Remove="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<EmbeddedResource Include="Search\Assets\CaseSensitive.png" />
<EmbeddedResource Include="Search\Assets\CompleteWord.png" />
<EmbeddedResource Include="Search\Assets\FindNext.png" />
<EmbeddedResource Include="Search\Assets\FindPrevious.png" />
<EmbeddedResource Include="Search\Assets\RegularExpression.png" />
<EmbeddedResource Include="Search\Assets\ReplaceAll.png" />
<EmbeddedResource Include="Search\Assets\ReplaceNext.png" />
</ItemGroup>
<ItemGroup>
<PackageReference Include="Avalonia" Version="$(AvaloniaVersion)" />
<PackageReference Include="System.Collections.Immutable" Version="1.6.0" />
</ItemGroup>
<ItemGroup>
<Compile Update="SR.Designer.cs">
<DesignTime>True</DesignTime>
<AutoGen>True</AutoGen>
<DependentUpon>SR.resx</DependentUpon>
</Compile>
</ItemGroup>
<ItemGroup>
<EmbeddedResource Update="SR.resx">
<Generator>PublicResXFileCodeGenerator</Generator>
<LastGenOutput>SR.Designer.cs</LastGenOutput>
</EmbeddedResource>
</ItemGroup>
<Target Name="ChangeAliasesOfSystemDrawing" BeforeTargets="FindReferenceAssembliesForReferences;ResolveReferences">
<ItemGroup>
<ReferencePath Condition="'%(FileName)' == 'Splat'">
<Aliases>SystemDrawing</Aliases>
</ReferencePath>
</ItemGroup>
</Target>
</Project>
<MSG> update avalonia.
<DFF> @@ -9,7 +9,7 @@
</ItemGroup>
<ItemGroup>
- <PackageReference Include="Avalonia" Version="0.5.2-build4356-alpha" />
+ <PackageReference Include="Avalonia" Version="0.5.2-build4358-alpha" />
<PackageReference Include="System.Collections.Immutable" Version="1.4.0" />
<PackageReference Include="System.Xml.ReaderWriter" Version="4.3.0" />
</ItemGroup>
| 1 | update avalonia. | 1 | .csproj | csproj | mit | AvaloniaUI/AvaloniaEdit |
10067923 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067924 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067925 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067926 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067927 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067928 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067929 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067930 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067931 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067932 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067933 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067934 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067935 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067936 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067937 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> Merge pull request #153 from AvaloniaUI/textDecorations
Underlines and Strikethrough support
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | Merge pull request #153 from AvaloniaUI/textDecorations | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067938 | <NME> web.js
<BEF> <%= namespace %> = (function (<%= param %>) {
<%= contents %>
})(<%= global %>);
<MSG> code cleanup
<DFF> @@ -1,3 +1,3 @@
-<%= namespace %> = (function (<%= param %>) {
+window.<%= namespace %> = (function (<%= param %>) {
<%= contents %>
})(<%= global %>);
| 1 | code cleanup | 1 | .js | js | mit | muicss/loadjs |
10067939 | <NME> web.js
<BEF> <%= namespace %> = (function (<%= param %>) {
<%= contents %>
})(<%= global %>);
<MSG> code cleanup
<DFF> @@ -1,3 +1,3 @@
-<%= namespace %> = (function (<%= param %>) {
+window.<%= namespace %> = (function (<%= param %>) {
<%= contents %>
})(<%= global %>);
| 1 | code cleanup | 1 | .js | js | mit | muicss/loadjs |
10067940 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> support underline and strikethrough: #109
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | support underline and strikethrough: #109 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067941 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> support underline and strikethrough: #109
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | support underline and strikethrough: #109 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067942 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> support underline and strikethrough: #109
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | support underline and strikethrough: #109 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067943 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> support underline and strikethrough: #109
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | support underline and strikethrough: #109 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067944 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> support underline and strikethrough: #109
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | support underline and strikethrough: #109 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067945 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> support underline and strikethrough: #109
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | support underline and strikethrough: #109 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067946 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> support underline and strikethrough: #109
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | support underline and strikethrough: #109 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067947 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> support underline and strikethrough: #109
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | support underline and strikethrough: #109 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067948 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> support underline and strikethrough: #109
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | support underline and strikethrough: #109 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
10067949 | <NME> XshdColor.cs
<BEF> // Copyright (c) 2014 AlphaSierraPapa for the SharpDevelop Team
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of this
// software and associated documentation files (the "Software"), to deal in the Software
// without restriction, including without limitation the rights to use, copy, modify, merge,
// publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons
// to whom the Software is furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all copies or
// substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED,
// INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
// PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE
// FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
// DEALINGS IN THE SOFTWARE.
using Avalonia.Media;
namespace AvaloniaEdit.Highlighting.Xshd
{
/// <summary>
/// A color in an Xshd file.
/// </summary>
public class XshdColor : XshdElement
{
/// <summary>
/// Gets/sets the name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Gets/sets the foreground brush.
/// </summary>
public HighlightingBrush Foreground { get; set; }
/// <summary>
/// Gets/sets the background brush.
/// </summary>
public HighlightingBrush Background { get; set; }
/// <summary>
/// Gets/sets the font family
/// </summary>
public FontFamily FontFamily { get; set; }
/// <summary>
/// Gets/sets the font size.
/// </summary>
public int? FontSize { get; set; }
/// <summary>
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
/// <summary>
/// Gets/sets the font style.
/// </summary>
public FontStyle? FontStyle { get; set; }
/// <summary>
/// Gets/Sets the example text that demonstrates where the color is used.
/// </summary>
public string ExampleText { get; set; }
///// <summary>
///// Serializes this XshdColor instance.
///// </summary>
//public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
//{
// if (info == null)
// throw new ArgumentNullException("info");
// info.AddValue("Name", this.Name);
// info.AddValue("Foreground", this.Foreground);
// info.AddValue("Background", this.Background);
// info.AddValue("HasUnderline", this.Underline.HasValue);
// if (this.Underline.HasValue)
// info.AddValue("Underline", this.Underline.Value);
// info.AddValue("HasWeight", this.FontWeight.HasValue);
// if (this.FontWeight.HasValue)
// info.AddValue("Weight", this.FontWeight.Value.ToOpenTypeWeight());
// info.AddValue("HasStyle", this.FontStyle.HasValue);
// if (this.FontStyle.HasValue)
// info.AddValue("Style", this.FontStyle.Value.ToString());
// info.AddValue("ExampleText", this.ExampleText);
//}
/// <inheritdoc/>
public override object AcceptVisitor(IXshdVisitor visitor)
{
return visitor.VisitColor(this);
}
}
}
<MSG> support underline and strikethrough: #109
<DFF> @@ -54,12 +54,17 @@ namespace AvaloniaEdit.Highlighting.Xshd
/// Gets/sets the font weight.
/// </summary>
public FontWeight? FontWeight { get; set; }
-
+
/// <summary>
/// Gets/sets the underline flag
/// </summary>
public bool? Underline { get; set; }
-
+
+ /// <summary>
+ /// Gets/sets the strikethrough flag
+ /// </summary>
+ public bool? Strikethrough { get; set; }
+
/// <summary>
/// Gets/sets the font style.
/// </summary>
| 7 | support underline and strikethrough: #109 | 2 | .cs | cs | mit | AvaloniaUI/AvaloniaEdit |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.