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
10067350
<NME> view.js <BEF> var fruitmachine = require('../../../../lib/'); // Require these views so that // fruitmachine registers them var LayoutA = require('../layout-a'); var ModuleApple = require('../module-apple'); var ModuleOrange = require('../module-orange'); var ModuleBanana = require('../module-banana'); module.exports = function(data) { var layout = { module: 'layout-a', children: [ { id: 'slot_1', module: 'orange' }, { id: 'slot_2', module: 'apple', data: { title: data.title } }, { id: 'slot_3', module: 'banana' } ] }; return fruitmachine(layout); }; <MSG> Update docs and examples to change "data" to "model" The "data" argument when instantiating modules has been deprecated in favour of "model"; update the docs and examples to reflect this new usage. Also fix a couple of links on the Rendering documentation page. <DFF> @@ -18,7 +18,7 @@ module.exports = function(data) { { id: 'slot_2', module: 'apple', - data: { + model: { title: data.title } },
1
Update docs and examples to change "data" to "model"
1
.js
js
mit
ftlabs/fruitmachine
10067351
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067352
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067353
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067354
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067355
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067356
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067357
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067358
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067359
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067360
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067361
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067362
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067363
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067364
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067365
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> update to avalonia 0.9 release <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>7.1</LangVersion> <TreatWarningsAsErrors>true</TreatWarningsAsErrors> - <AvaloniaVersion>0.9.0-rc.2</AvaloniaVersion> + <AvaloniaVersion>0.9.0</AvaloniaVersion> </PropertyGroup> </Project> \ No newline at end of file
1
update to avalonia 0.9 release
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067366
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067367
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067368
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067369
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067370
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067371
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067372
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067373
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067374
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067375
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067376
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067377
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067378
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067379
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067380
<NME> Directory.Build.props <BEF> <Project> <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> <AvaloniaVersion>0.10.6</AvaloniaVersion> </PropertyGroup> </Project> <VersionSuffix>beta</VersionSuffix> </PropertyGroup> </Project> <MSG> Update to Avalonia 0.10.10 <DFF> @@ -2,6 +2,6 @@ <PropertyGroup> <LangVersion>latest</LangVersion> <TreatWarningsAsErrors>false</TreatWarningsAsErrors> - <AvaloniaVersion>0.10.6</AvaloniaVersion> + <AvaloniaVersion>0.10.10</AvaloniaVersion> </PropertyGroup> </Project>
1
Update to Avalonia 0.10.10
1
.props
Build
mit
AvaloniaUI/AvaloniaEdit
10067381
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067382
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067383
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067384
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067385
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067386
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067387
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067388
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067389
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067390
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067391
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067392
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067393
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067394
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067395
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent { #region Constructors static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); searchPanel = SearchPanel.Install(this); } /// <summary> /// Gets the text area. /// </summary> /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Encoding dependency property. /// </summary> public static readonly StyledProperty<Encoding> EncodingProperty = AvaloniaProperty.Register<TextEditor, Encoding>("Encoding"); /// <summary> /// Gets/sets the encoding used when the file is saved. /// </summary> /// <remarks> /// The <see cref="Load(Stream)"/> method autodetects the encoding of the file and sets this property accordingly. /// The <see cref="Save(Stream)"/> method uses the encoding specified in this property. /// </remarks> public Encoding Encoding { get => GetValue(EncodingProperty); set => SetValue(EncodingProperty, value); } /// <summary> /// Saves the text to the stream. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Save(Stream stream) { if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Hide the search panel when detaching from logical tree, and restore it when attaching <DFF> @@ -32,6 +32,7 @@ using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; +using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; @@ -283,6 +284,7 @@ namespace AvaloniaEdit #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; + private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { @@ -293,6 +295,27 @@ namespace AvaloniaEdit searchPanel = SearchPanel.Install(this); } + protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnAttachedToLogicalTree(e); + + if (searchPanel != null && wasSearchPanelOpened) + { + searchPanel.Open(); + } + } + + protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) + { + base.OnDetachedFromLogicalTree(e); + + if (searchPanel != null) + { + wasSearchPanelOpened = !searchPanel.IsClosed; + searchPanel.Close(); + } + } + /// <summary> /// Gets the text area. /// </summary>
23
Hide the search panel when detaching from logical tree, and restore it when attaching
0
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067396
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067397
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067398
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067399
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067400
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067401
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067402
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067403
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067404
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067405
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067406
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067407
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067408
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067409
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067410
<NME> TextEditor.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.ComponentModel; using System.IO; using System.Linq; using System.Text; using Avalonia; using AvaloniaEdit.Document; using AvaloniaEdit.Editing; using AvaloniaEdit.Highlighting; using AvaloniaEdit.Rendering; using AvaloniaEdit.Utils; using Avalonia.Controls; using Avalonia.Controls.Primitives; using Avalonia.Controls.Shapes; using Avalonia.Input; using Avalonia.Interactivity; using Avalonia.LogicalTree; using Avalonia.Media; using Avalonia.Data; using AvaloniaEdit.Search; namespace AvaloniaEdit { /// <summary> /// The text editor control. /// Contains a scrollable TextArea. /// </summary> public class TextEditor : TemplatedControl, ITextEditorComponent static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); SyntaxHighlightingProperty.Changed.Subscribe(OnSyntaxHighlightingChanged); IsReadOnlyProperty.Changed.Subscribe(OnIsReadOnlyChanged); IsModifiedProperty.Changed.Subscribe(OnIsModifiedChanged); ShowLineNumbersProperty.Changed.Subscribe(OnShowLineNumbersChanged); LineNumbersForegroundProperty.Changed.Subscribe(OnLineNumbersForegroundChanged); FontFamilyProperty.Changed.Subscribe(OnFontFamilyPropertyChanged); FontSizeProperty.Changed.Subscribe(OnFontSizePropertyChanged); } /// <summary> /// Creates a new TextEditor instance. /// </summary> public TextEditor() : this(new TextArea()) { } /// <summary> /// Creates a new TextEditor instance. /// </summary> protected TextEditor(TextArea textArea) : this(textArea, new TextDocument()) { } protected TextEditor(TextArea textArea, TextDocument document) { this.textArea = textArea ?? throw new ArgumentNullException(nameof(textArea)); textArea.TextView.Services.AddService(this); SetValue(OptionsProperty, textArea.Options); SetValue(DocumentProperty, document); textArea[!BackgroundProperty] = this[!BackgroundProperty]; } #endregion protected override void OnGotFocus(GotFocusEventArgs e) { base.OnGotFocus(e); TextArea.Focus(); e.Handled = true; } #region Document property /// <summary> /// Document property. /// </summary> public static readonly StyledProperty<TextDocument> DocumentProperty = TextView.DocumentProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the document displayed by the text editor. /// This is a dependency property. /// </summary> public TextDocument Document { get => GetValue(DocumentProperty); set => SetValue(DocumentProperty, value); } /// <summary> /// Occurs when the document property has changed. /// </summary> public event EventHandler DocumentChanged; /// <summary> /// Raises the <see cref="DocumentChanged"/> event. /// </summary> protected virtual void OnDocumentChanged(EventArgs e) { DocumentChanged?.Invoke(this, e); } private static void OnDocumentChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnDocumentChanged((TextDocument)e.OldValue, (TextDocument)e.NewValue); } private void OnDocumentChanged(TextDocument oldValue, TextDocument newValue) { if (oldValue != null) { TextDocumentWeakEventManager.TextChanged.RemoveHandler(oldValue, OnTextChanged); PropertyChangedWeakEventManager.RemoveHandler(oldValue.UndoStack, OnUndoStackPropertyChangedHandler); } TextArea.Document = newValue; if (newValue != null) { TextDocumentWeakEventManager.TextChanged.AddHandler(newValue, OnTextChanged); PropertyChangedWeakEventManager.AddHandler(newValue.UndoStack, OnUndoStackPropertyChangedHandler); } OnDocumentChanged(EventArgs.Empty); OnTextChanged(EventArgs.Empty); } #endregion #region Options property /// <summary> /// Options property. /// </summary> public static readonly StyledProperty<TextEditorOptions> OptionsProperty = TextView.OptionsProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the options currently 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); } private static void OnOptionsChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnOptionsChanged((TextEditorOptions)e.OldValue, (TextEditorOptions)e.NewValue); } private void OnOptionsChanged(TextEditorOptions oldValue, TextEditorOptions newValue) { if (oldValue != null) { PropertyChangedWeakEventManager.RemoveHandler(oldValue, OnPropertyChangedHandler); } TextArea.Options = newValue; if (newValue != null) { PropertyChangedWeakEventManager.AddHandler(newValue, OnPropertyChangedHandler); } OnOptionChanged(new PropertyChangedEventArgs(null)); } private void OnPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { OnOptionChanged(e); } protected override void OnPropertyChanged(AvaloniaPropertyChangedEventArgs change) { base.OnPropertyChanged(change); if (change.Property == WordWrapProperty) { if (WordWrap) { _horizontalScrollBarVisibilityBck = HorizontalScrollBarVisibility; HorizontalScrollBarVisibility = ScrollBarVisibility.Disabled; } else { HorizontalScrollBarVisibility = _horizontalScrollBarVisibilityBck; } } } private void OnUndoStackPropertyChangedHandler(object sender, PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { HandleIsOriginalChanged(e); } } private void OnTextChanged(object sender, EventArgs e) { OnTextChanged(e); } #endregion #region Text property /// <summary> /// Gets/Sets the text of the current document. /// </summary> public string Text { get { var document = Document; return document != null ? document.Text : string.Empty; } set { var document = GetDocument(); document.Text = value ?? string.Empty; // after replacing the full text, the caret is positioned at the end of the document // - reset it to the beginning. CaretOffset = 0; document.UndoStack.ClearAll(); } } private TextDocument GetDocument() { var document = Document; if (document == null) throw ThrowUtil.NoDocumentAssigned(); return document; } /// <summary> /// Occurs when the Text property changes. /// </summary> public event EventHandler TextChanged; /// <summary> /// Raises the <see cref="TextChanged"/> event. /// </summary> protected virtual void OnTextChanged(EventArgs e) { TextChanged?.Invoke(this, e); } #endregion #region TextArea / ScrollViewer properties private readonly TextArea textArea; private SearchPanel searchPanel; private bool wasSearchPanelOpened; protected override void OnApplyTemplate(TemplateAppliedEventArgs e) { base.OnApplyTemplate(e); ScrollViewer = (ScrollViewer)e.NameScope.Find("PART_ScrollViewer"); ScrollViewer.Content = TextArea; searchPanel = SearchPanel.Install(this); } protected override void OnAttachedToLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnAttachedToLogicalTree(e); if (searchPanel != null && wasSearchPanelOpened) { searchPanel.Open(); } } protected override void OnDetachedFromLogicalTree(LogicalTreeAttachmentEventArgs e) { base.OnDetachedFromLogicalTree(e); if (searchPanel != null) { wasSearchPanelOpened = searchPanel.IsOpened; if (searchPanel.IsOpened) searchPanel.Close(); } } /// <summary> /// Gets the text area. /// </summary> public TextArea TextArea => textArea; /// <summary> /// Gets the search panel. /// </summary> public SearchPanel SearchPanel => searchPanel; /// <summary> /// Gets the scroll viewer used by the text editor. /// This property can return null if the template has not been applied / does not contain a scroll viewer. /// </summary> internal ScrollViewer ScrollViewer { get; private set; } #endregion #region Syntax highlighting /// <summary> /// The <see cref="SyntaxHighlighting"/> property. /// </summary> public static readonly StyledProperty<IHighlightingDefinition> SyntaxHighlightingProperty = AvaloniaProperty.Register<TextEditor, IHighlightingDefinition>("SyntaxHighlighting"); /// <summary> /// Gets/sets the syntax highlighting definition used to colorize the text. /// </summary> public IHighlightingDefinition SyntaxHighlighting { get => GetValue(SyntaxHighlightingProperty); set => SetValue(SyntaxHighlightingProperty, value); } private IVisualLineTransformer _colorizer; private static void OnSyntaxHighlightingChanged(AvaloniaPropertyChangedEventArgs e) { (e.Sender as TextEditor)?.OnSyntaxHighlightingChanged(e.NewValue as IHighlightingDefinition); } private void OnSyntaxHighlightingChanged(IHighlightingDefinition newValue) { if (_colorizer != null) { textArea.TextView.LineTransformers.Remove(_colorizer); _colorizer = null; } if (newValue != null) { _colorizer = CreateColorizer(newValue); if (_colorizer != null) { textArea.TextView.LineTransformers.Insert(0, _colorizer); } } } /// <summary> /// Creates the highlighting colorizer for the specified highlighting definition. /// Allows derived classes to provide custom colorizer implementations for special highlighting definitions. /// </summary> /// <returns></returns> protected virtual IVisualLineTransformer CreateColorizer(IHighlightingDefinition highlightingDefinition) { if (highlightingDefinition == null) throw new ArgumentNullException(nameof(highlightingDefinition)); return new HighlightingColorizer(highlightingDefinition); } #endregion #region WordWrap /// <summary> /// Word wrap dependency property. /// </summary> public static readonly StyledProperty<bool> WordWrapProperty = AvaloniaProperty.Register<TextEditor, bool>("WordWrap"); /// <summary> /// Specifies whether the text editor uses word wrapping. /// </summary> /// <remarks> /// Setting WordWrap=true has the same effect as setting HorizontalScrollBarVisibility=Disabled and will override the /// HorizontalScrollBarVisibility setting. /// </remarks> public bool WordWrap { get => GetValue(WordWrapProperty); set => SetValue(WordWrapProperty, value); } #endregion #region IsReadOnly /// <summary> /// IsReadOnly dependency property. /// </summary> public static readonly StyledProperty<bool> IsReadOnlyProperty = AvaloniaProperty.Register<TextEditor, bool>("IsReadOnly"); /// <summary> /// Specifies whether the user can change the text editor content. /// Setting this property will replace the /// <see cref="Editing.TextArea.ReadOnlySectionProvider">TextArea.ReadOnlySectionProvider</see>. /// </summary> public bool IsReadOnly { get => GetValue(IsReadOnlyProperty); set => SetValue(IsReadOnlyProperty, value); } private static void OnIsReadOnlyChanged(AvaloniaPropertyChangedEventArgs e) { if (e.Sender is TextEditor editor) { if ((bool)e.NewValue) editor.TextArea.ReadOnlySectionProvider = ReadOnlySectionDocument.Instance; else editor.TextArea.ReadOnlySectionProvider = NoReadOnlySections.Instance; } } #endregion #region IsModified /// <summary> /// Dependency property for <see cref="IsModified"/> /// </summary> public static readonly StyledProperty<bool> IsModifiedProperty = AvaloniaProperty.Register<TextEditor, bool>("IsModified"); /// <summary> /// Gets/Sets the 'modified' flag. /// </summary> public bool IsModified { get => GetValue(IsModifiedProperty); set => SetValue(IsModifiedProperty, value); } private static void OnIsModifiedChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var document = editor?.Document; if (document != null) { var undoStack = document.UndoStack; if ((bool)e.NewValue) { if (undoStack.IsOriginalFile) undoStack.DiscardOriginalFileMarker(); } else { undoStack.MarkAsOriginalFile(); } } } private void HandleIsOriginalChanged(PropertyChangedEventArgs e) { if (e.PropertyName == "IsOriginalFile") { var document = Document; if (document != null) { SetValue(IsModifiedProperty, (object)!document.UndoStack.IsOriginalFile); } } } #endregion #region ShowLineNumbers /// <summary> /// ShowLineNumbers dependency property. /// </summary> public static readonly StyledProperty<bool> ShowLineNumbersProperty = AvaloniaProperty.Register<TextEditor, bool>("ShowLineNumbers"); /// <summary> /// Specifies whether line numbers are shown on the left to the text view. /// </summary> public bool ShowLineNumbers { get => GetValue(ShowLineNumbersProperty); set => SetValue(ShowLineNumbersProperty, value); } private static void OnShowLineNumbersChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; if (editor == null) return; var leftMargins = editor.TextArea.LeftMargins; if ((bool)e.NewValue) { var lineNumbers = new LineNumberMargin(); var line = (Line)DottedLineMargin.Create(); leftMargins.Insert(0, lineNumbers); leftMargins.Insert(1, line); var lineNumbersForeground = new Binding("LineNumbersForeground") { Source = editor }; line.Bind(Shape.StrokeProperty, lineNumbersForeground); lineNumbers.Bind(ForegroundProperty, lineNumbersForeground); } else { for (var i = 0; i < leftMargins.Count; i++) { if (leftMargins[i] is LineNumberMargin) { leftMargins.RemoveAt(i); if (i < leftMargins.Count && DottedLineMargin.IsDottedLineMargin(leftMargins[i])) { leftMargins.RemoveAt(i); } break; } } } } #endregion #region LineNumbersForeground /// <summary> /// LineNumbersForeground dependency property. /// </summary> public static readonly StyledProperty<IBrush> LineNumbersForegroundProperty = AvaloniaProperty.Register<TextEditor, IBrush>("LineNumbersForeground", Brushes.Gray); /// <summary> /// Gets/sets the Brush used for displaying the foreground color of line numbers. /// </summary> public IBrush LineNumbersForeground { get => GetValue(LineNumbersForegroundProperty); set => SetValue(LineNumbersForegroundProperty, value); } private static void OnLineNumbersForegroundChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; var lineNumberMargin = editor?.TextArea.LeftMargins.FirstOrDefault(margin => margin is LineNumberMargin) as LineNumberMargin; lineNumberMargin?.SetValue(ForegroundProperty, e.NewValue); } private static void OnFontFamilyPropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontFamilyProperty, e.NewValue); } private static void OnFontSizePropertyChanged(AvaloniaPropertyChangedEventArgs e) { var editor = e.Sender as TextEditor; editor?.TextArea.TextView.SetValue(FontSizeProperty, e.NewValue); } #endregion #region TextBoxBase-like methods /// <summary> /// Appends text to the end of the document. /// </summary> public void AppendText(string textData) { var document = GetDocument(); document.Insert(document.TextLength, textData); } /// <summary> /// Begins a group of document changes. /// </summary> public void BeginChange() { GetDocument().BeginUpdate(); } /// <summary> /// Copies the current selection to the clipboard. /// </summary> public void Copy() { if (CanCopy) { ApplicationCommands.Copy.Execute(null, TextArea); } } /// <summary> /// Removes the current selection and copies it to the clipboard. /// </summary> public void Cut() { if (CanCut) { ApplicationCommands.Cut.Execute(null, TextArea); } } /// <summary> /// Begins a group of document changes and returns an object that ends the group of document /// changes when it is disposed. /// </summary> public IDisposable DeclareChangeBlock() { return GetDocument().RunUpdate(); } /// <summary> /// Removes the current selection without copying it to the clipboard. /// </summary> public void Delete() { if(CanDelete) { ApplicationCommands.Delete.Execute(null, TextArea); } } /// <summary> /// Ends the current group of document changes. /// </summary> public void EndChange() { GetDocument().EndUpdate(); } /// <summary> /// Scrolls one line down. /// </summary> public void LineDown() { //if (scrollViewer != null) // scrollViewer.LineDown(); } /// <summary> /// Scrolls to the left. /// </summary> public void LineLeft() { //if (scrollViewer != null) // scrollViewer.LineLeft(); } /// <summary> /// Scrolls to the right. /// </summary> public void LineRight() { //if (scrollViewer != null) // scrollViewer.LineRight(); } /// <summary> /// Scrolls one line up. /// </summary> public void LineUp() { //if (scrollViewer != null) // scrollViewer.LineUp(); } /// <summary> /// Scrolls one page down. /// </summary> public void PageDown() { //if (scrollViewer != null) // scrollViewer.PageDown(); } /// <summary> /// Scrolls one page up. /// </summary> public void PageUp() { //if (scrollViewer != null) // scrollViewer.PageUp(); } /// <summary> /// Scrolls one page left. /// </summary> public void PageLeft() { //if (scrollViewer != null) // scrollViewer.PageLeft(); } /// <summary> /// Scrolls one page right. /// </summary> public void PageRight() { //if (scrollViewer != null) // scrollViewer.PageRight(); } /// <summary> /// Pastes the clipboard content. /// </summary> public void Paste() { if (CanPaste) { ApplicationCommands.Paste.Execute(null, TextArea); } } /// <summary> /// Redoes the most recent undone command. /// </summary> /// <returns>True is the redo operation was successful, false is the redo stack is empty.</returns> public bool Redo() { if (CanRedo) { ApplicationCommands.Redo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Scrolls to the end of the document. /// </summary> public void ScrollToEnd() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToEnd(); } /// <summary> /// Scrolls to the start of the document. /// </summary> public void ScrollToHome() { ApplyTemplate(); // ensure scrollViewer is created ScrollViewer?.ScrollToHome(); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToHorizontalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToHorizontalOffset(offset); } /// <summary> /// Scrolls to the specified position in the document. /// </summary> public void ScrollToVerticalOffset(double offset) { ApplyTemplate(); // ensure scrollViewer is created //if (scrollViewer != null) // scrollViewer.ScrollToVerticalOffset(offset); } /// <summary> /// Selects the entire text. /// </summary> public void SelectAll() { if (CanSelectAll) { ApplicationCommands.SelectAll.Execute(null, TextArea); } } /// <summary> /// Undoes the most recent command. /// </summary> /// <returns>True is the undo operation was successful, false is the undo stack is empty.</returns> public bool Undo() { if (CanUndo) { ApplicationCommands.Undo.Execute(null, TextArea); return true; } return false; } /// <summary> /// Gets if the most recent undone command can be redone. /// </summary> public bool CanRedo { get { return ApplicationCommands.Redo.CanExecute(null, TextArea); } } /// <summary> /// Gets if the most recent command can be undone. /// </summary> public bool CanUndo { get { return ApplicationCommands.Undo.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be copied /// </summary> public bool CanCopy { get { return ApplicationCommands.Copy.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be cut /// </summary> public bool CanCut { get { return ApplicationCommands.Cut.CanExecute(null, TextArea); } } /// <summary> /// Gets if text in editor can be pasted /// </summary> public bool CanPaste { get { return ApplicationCommands.Paste.CanExecute(null, TextArea); } } /// <summary> /// Gets if selected text in editor can be deleted /// </summary> public bool CanDelete { get { return ApplicationCommands.Delete.CanExecute(null, TextArea); } } /// <summary> /// Gets if text the editor can select all /// </summary> public bool CanSelectAll { get { return ApplicationCommands.SelectAll.CanExecute(null, TextArea); } } /// <summary> /// Gets if text editor can activate the search panel /// </summary> public bool CanSearch { get { return searchPanel != null; } } /// <summary> /// Gets the vertical size of the document. /// </summary> public double ExtentHeight => ScrollViewer?.Extent.Height ?? 0; /// <summary> /// Gets the horizontal size of the current document region. /// </summary> public double ExtentWidth => ScrollViewer?.Extent.Width ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportHeight => ScrollViewer?.Viewport.Height ?? 0; /// <summary> /// Gets the horizontal size of the viewport. /// </summary> public double ViewportWidth => ScrollViewer?.Viewport.Width ?? 0; /// <summary> /// Gets the vertical scroll position. /// </summary> public double VerticalOffset => ScrollViewer?.Offset.Y ?? 0; /// <summary> /// Gets the horizontal scroll position. /// </summary> public double HorizontalOffset => ScrollViewer?.Offset.X ?? 0; #endregion #region TextBox methods /// <summary> /// Gets/Sets the selected text. /// </summary> public string SelectedText { get { // We'll get the text from the whole surrounding segment. // This is done to ensure that SelectedText.Length == SelectionLength. if (textArea.Document != null && !textArea.Selection.IsEmpty) return textArea.Document.GetText(textArea.Selection.SurroundingSegment); return string.Empty; } set { if (value == null) throw new ArgumentNullException(nameof(value)); var textArea = TextArea; if (textArea.Document != null) { var offset = SelectionStart; var length = SelectionLength; textArea.Document.Replace(offset, length, value); // keep inserted text selected textArea.Selection = Selection.Create(textArea, offset, offset + value.Length); } } } /// <summary> /// Gets/sets the caret position. /// </summary> public int CaretOffset { get { return textArea.Caret.Offset; } set { textArea.Caret.Offset = value; } } /// <summary> /// Gets/sets the start position of the selection. /// </summary> public int SelectionStart { get { if (textArea.Selection.IsEmpty) return textArea.Caret.Offset; else return textArea.Selection.SurroundingSegment.Offset; } set => Select(value, SelectionLength); } /// <summary> /// Gets/sets the length of the selection. /// </summary> public int SelectionLength { get { if (!textArea.Selection.IsEmpty) return textArea.Selection.SurroundingSegment.Length; else return 0; } set => Select(SelectionStart, value); } /// <summary> /// Selects the specified text section. /// </summary> public void Select(int start, int length) { var documentLength = Document?.TextLength ?? 0; if (start < 0 || start > documentLength) throw new ArgumentOutOfRangeException(nameof(start), start, "Value must be between 0 and " + documentLength); if (length < 0 || start + length > documentLength) throw new ArgumentOutOfRangeException(nameof(length), length, "Value must be between 0 and " + (documentLength - start)); TextArea.Selection = Selection.Create(TextArea, start, start + length); TextArea.Caret.Offset = start + length; } /// <summary> /// Gets the number of lines in the document. /// </summary> public int LineCount { get { var document = Document; if (document != null) return document.LineCount; return 1; } } /// <summary> /// Clears the text. /// </summary> public void Clear() { Text = string.Empty; } #endregion #region Loading from stream /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> /// <remarks> /// This method sets <see cref="IsModified"/> to false. /// </remarks> public void Load(Stream stream) { using (var reader = FileReader.OpenStream(stream, Encoding ?? Encoding.UTF8)) { Text = reader.ReadToEnd(); SetValue(EncodingProperty, (object)reader.CurrentEncoding); } SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Loads the text from the stream, auto-detecting the encoding. /// </summary> public void Load(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO:load //using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read)) //{ // Load(fs); //} } /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion if (stream == null) throw new ArgumentNullException(nameof(stream)); var encoding = Encoding; var document = Document; var writer = encoding != null ? new StreamWriter(stream, encoding) : new StreamWriter(stream); document?.WriteTextTo(writer); writer.Flush(); // do not close the stream SetValue(IsModifiedProperty, (object)false); } /// <summary> /// Saves the text to the file. /// </summary> public void Save(string fileName) { if (fileName == null) throw new ArgumentNullException(nameof(fileName)); // TODO: save //using (FileStream fs = new FileStream(fileName, FileMode.Create, FileAccess.Write, FileShare.None)) //{ // Save(fs); //} } #endregion #region PointerHover events /// <summary> /// The PreviewPointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverEvent = TextView.PreviewPointerHoverEvent; /// <summary> /// the pointerHover event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverEvent = TextView.PointerHoverEvent; /// <summary> /// The PreviewPointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PreviewPointerHoverStoppedEvent = TextView.PreviewPointerHoverStoppedEvent; /// <summary> /// the pointerHoverStopped event. /// </summary> public static readonly RoutedEvent<PointerEventArgs> PointerHoverStoppedEvent = TextView.PointerHoverStoppedEvent; /// <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 pointer 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); } #endregion #region ScrollBarVisibility /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } private ScrollBarVisibility _horizontalScrollBarVisibilityBck = ScrollBarVisibility.Auto; /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion object IServiceProvider.GetService(Type serviceType) { return TextArea.GetService(serviceType); } /// <summary> /// Gets the text view position from a point inside the editor. /// </summary> /// <param name="point">The position, relative to top left /// corner of TextEditor control</param> /// <returns>The text view position, or null if the point is outside the document.</returns> public TextViewPosition? GetPositionFromPoint(Point point) { if (Document == null) return null; var textView = TextArea.TextView; Point tpoint = (Point)this.TranslatePoint(point + new Point(textView.ScrollOffset.X, Math.Floor(textView.ScrollOffset.Y)), textView); return textView.GetPosition(tpoint); } /// <summary> /// Scrolls to the specified line. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollToLine(int line) { ScrollTo(line, -1); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (layout engine must have run prior). /// </summary> public void ScrollTo(int line, int column) { const double MinimumScrollFraction = 0.3; ScrollTo(line, column, VisualYPosition.LineMiddle, null != ScrollViewer ? ScrollViewer.Viewport.Height / 2 : 0.0, MinimumScrollFraction); } /// <summary> /// Scrolls to the specified line/column. /// This method requires that the TextEditor was already assigned a size (WPF layout must have run prior). /// </summary> /// <param name="line">Line to scroll to.</param> /// <param name="column">Column to scroll to (important if wrapping is 'on', and for the horizontal scroll position).</param> /// <param name="yPositionMode">The mode how to reference the Y position of the line.</param> /// <param name="referencedVerticalViewPortOffset">Offset from the top of the viewport to where the referenced line/column should be positioned.</param> /// <param name="minimumScrollFraction">The minimum vertical and/or horizontal scroll offset, expressed as fraction of the height or width of the viewport window, respectively.</param> public void ScrollTo(int line, int column, VisualYPosition yPositionMode, double referencedVerticalViewPortOffset, double minimumScrollFraction) { TextView textView = textArea.TextView; TextDocument document = textView.Document; if (ScrollViewer != null && document != null) { if (line < 1) line = 1; if (line > document.LineCount) line = document.LineCount; ILogicalScrollable scrollInfo = textView; if (!scrollInfo.CanHorizontallyScroll) { // Word wrap is enabled. Ensure that we have up-to-date info about line height so that we scroll // to the correct position. // This avoids that the user has to repeat the ScrollTo() call several times when there are very long lines. VisualLine vl = textView.GetOrConstructVisualLine(document.GetLineByNumber(line)); double remainingHeight = referencedVerticalViewPortOffset; while (remainingHeight > 0) { DocumentLine prevLine = vl.FirstDocumentLine.PreviousLine; if (prevLine == null) break; vl = textView.GetOrConstructVisualLine(prevLine); remainingHeight -= vl.Height; } } Point p = textArea.TextView.GetVisualPosition( new TextViewPosition(line, Math.Max(1, column)), yPositionMode); double targetX = ScrollViewer.Offset.X; double targetY = ScrollViewer.Offset.Y; double verticalPos = p.Y - referencedVerticalViewPortOffset; if (Math.Abs(verticalPos - ScrollViewer.Offset.Y) > minimumScrollFraction * ScrollViewer.Viewport.Height) { targetY = Math.Max(0, verticalPos); } if (column > 0) { if (p.X > ScrollViewer.Viewport.Width - Caret.MinimumDistanceToViewBorder * 2) { double horizontalPos = Math.Max(0, p.X - ScrollViewer.Viewport.Width / 2); if (Math.Abs(horizontalPos - ScrollViewer.Offset.X) > minimumScrollFraction * ScrollViewer.Viewport.Width) { targetX = 0; } } else { targetX = 0; } } if (targetX != ScrollViewer.Offset.X || targetY != ScrollViewer.Offset.Y) ScrollViewer.Offset = new Vector(targetX, targetY); } } } } <MSG> Merge pull request #48 from AvaloniaUI/fix-scroll Fix horizontal scroll <DFF> @@ -47,6 +47,8 @@ namespace AvaloniaEdit static TextEditor() { FocusableProperty.OverrideDefaultValue<TextEditor>(true); + HorizontalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); + VerticalScrollBarVisibilityProperty.OverrideDefaultValue<TextEditor>(ScrollBarVisibility.Auto); OptionsProperty.Changed.Subscribe(OnOptionsChanged); DocumentProperty.Changed.Subscribe(OnDocumentChanged); @@ -1049,28 +1051,28 @@ namespace AvaloniaEdit /// <summary> /// Dependency property for <see cref="HorizontalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> HorizontalScrollBarVisibilityProperty = ScrollViewer.HorizontalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the horizontal scroll bar visibility. /// </summary> public ScrollBarVisibility HorizontalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(HorizontalScrollBarVisibilityProperty); + get => GetValue(HorizontalScrollBarVisibilityProperty); set => SetValue(HorizontalScrollBarVisibilityProperty, value); } /// <summary> /// Dependency property for <see cref="VerticalScrollBarVisibility"/> /// </summary> - public static readonly AvaloniaProperty VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); + public static readonly AttachedProperty<ScrollBarVisibility> VerticalScrollBarVisibilityProperty = ScrollViewer.VerticalScrollBarVisibilityProperty.AddOwner<TextEditor>(); /// <summary> /// Gets/Sets the vertical scroll bar visibility. /// </summary> public ScrollBarVisibility VerticalScrollBarVisibility { - get => (ScrollBarVisibility)GetValue(VerticalScrollBarVisibilityProperty); + get => GetValue(VerticalScrollBarVisibilityProperty); set => SetValue(VerticalScrollBarVisibilityProperty, value); } #endregion
6
Merge pull request #48 from AvaloniaUI/fix-scroll
4
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067411
<NME> loadjs.min.js <BEF> loadjs=function(){var l=function(){},c={},f={},u={};function s(e,n){if(e){var t=u[e];if(f[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function o(e,n){e.call&&(e={success:e}),n.length?(e.error||l)(n):(e.success||l)(e)}function h(t,r,i,c){var s,o,e=document,n=i.async,f=(i.numRetries||0)+1,u=i.before||l,a=t.replace(/^(css|img)!/,"");c=c||0,/(^css!|\.css$)/.test(t)?(s=!0,(o=e.createElement("link")).rel="stylesheet",o.href=a):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(o=e.createElement("img")).src=a:((o=e.createElement("script")).src=t,o.async=void 0===n||n),!(o.onload=o.onerror=o.onbeforeload=function(e){var n=e.type[0];if(s&&"hideFocus"in o)try{o.sheet.cssText.length||(n="e")}catch(e){n="e"}if("e"==n&&(c+=1)<f)return h(t,r,i,c);r(t,n,e.defaultPrevented)})!==u(t,o)&&e.head.appendChild(o)}function t(e,n,t){var r,i;if(n&&n.trim&&(r=n),i=(r?t:n)||{},r){if(r in c)throw"LoadJS";c[r]=!0}!function(e,r,n){var t,i,c=(e=e.push?e:[e]).length,s=c,o=[];for(t=function(e,n,t){if("e"==n&&o.push(e),"b"==n){if(!t)return;o.push(e)}--c||r(o)},i=0;i<s;i++)h(e[i],t,n)}(e,function(e){o(i,e),s(r,e)},i)}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,i,c=[],s=e.length,o=s;for(n=function(e,n){n.length&&c.push(e),--o||t(c)};s--;)r=e[s],(i=f[r])?n(r,i):(u[r]=u[r]||[]).push(n)}(e,function(e){o(n,e)}),t},t.done=function(e){s(e,[])},t.reset=function(){c={},f={},u={}},t.isDefined=function(e){return e in c},t}(); <MSG> bumped version number <DFF> @@ -1,1 +1,1 @@ -loadjs=function(){var l=function(){},c={},f={},u={};function s(e,n){if(e){var t=u[e];if(f[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function o(e,n){e.call&&(e={success:e}),n.length?(e.error||l)(n):(e.success||l)(e)}function h(t,r,i,c){var s,o,e=document,n=i.async,f=(i.numRetries||0)+1,u=i.before||l,a=t.replace(/^(css|img)!/,"");c=c||0,/(^css!|\.css$)/.test(t)?(s=!0,(o=e.createElement("link")).rel="stylesheet",o.href=a):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(o=e.createElement("img")).src=a:((o=e.createElement("script")).src=t,o.async=void 0===n||n),!(o.onload=o.onerror=o.onbeforeload=function(e){var n=e.type[0];if(s&&"hideFocus"in o)try{o.sheet.cssText.length||(n="e")}catch(e){n="e"}if("e"==n&&(c+=1)<f)return h(t,r,i,c);r(t,n,e.defaultPrevented)})!==u(t,o)&&e.head.appendChild(o)}function t(e,n,t){var r,i;if(n&&n.trim&&(r=n),i=(r?t:n)||{},r){if(r in c)throw"LoadJS";c[r]=!0}!function(e,r,n){var t,i,c=(e=e.push?e:[e]).length,s=c,o=[];for(t=function(e,n,t){if("e"==n&&o.push(e),"b"==n){if(!t)return;o.push(e)}--c||r(o)},i=0;i<s;i++)h(e[i],t,n)}(e,function(e){o(i,e),s(r,e)},i)}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,i,c=[],s=e.length,o=s;for(n=function(e,n){n.length&&c.push(e),--o||t(c)};s--;)r=e[s],(i=f[r])?n(r,i):(u[r]=u[r]||[]).push(n)}(e,function(e){o(n,e)}),t},t.done=function(e){s(e,[])},t.reset=function(){c={},f={},u={}},t.isDefined=function(e){return e in c},t}(); \ No newline at end of file +loadjs=function(){var l=function(){},c={},f={},u={};function o(e,n){if(e){var t=u[e];if(f[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function s(e,n){e.call&&(e={success:e}),n.length?(e.error||l)(n):(e.success||l)(e)}function h(t,r,i,c){var o,s,e=document,n=i.async,f=(i.numRetries||0)+1,u=i.before||l,a=t.replace(/^(css|img)!/,"");c=c||0,/(^css!|\.css$)/.test(t)?(o=!0,(s=e.createElement("link")).rel="stylesheet",s.href=a):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(s=e.createElement("img")).src=a:((s=e.createElement("script")).src=t,s.async=void 0===n||n),!(s.onload=s.onerror=s.onbeforeload=function(e){var n=e.type[0];if(o&&"hideFocus"in s)try{s.sheet.cssText.length||(n="e")}catch(e){18!=e.code&&(n="e")}if("e"==n&&(c+=1)<f)return h(t,r,i,c);r(t,n,e.defaultPrevented)})!==u(t,s)&&e.head.appendChild(s)}function t(e,n,t){var r,i;if(n&&n.trim&&(r=n),i=(r?t:n)||{},r){if(r in c)throw"LoadJS";c[r]=!0}!function(e,r,n){var t,i,c=(e=e.push?e:[e]).length,o=c,s=[];for(t=function(e,n,t){if("e"==n&&s.push(e),"b"==n){if(!t)return;s.push(e)}--c||r(s)},i=0;i<o;i++)h(e[i],t,n)}(e,function(e){s(i,e),o(r,e)},i)}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,i,c=[],o=e.length,s=o;for(n=function(e,n){n.length&&c.push(e),--s||t(c)};o--;)r=e[o],(i=f[r])?n(r,i):(u[r]=u[r]||[]).push(n)}(e,function(e){s(n,e)}),t},t.done=function(e){o(e,[])},t.reset=function(){c={},f={},u={}},t.isDefined=function(e){return e in c},t}(); \ No newline at end of file
1
bumped version number
1
.js
min
mit
muicss/loadjs
10067412
<NME> loadjs.min.js <BEF> loadjs=function(){var l=function(){},c={},f={},u={};function s(e,n){if(e){var t=u[e];if(f[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function o(e,n){e.call&&(e={success:e}),n.length?(e.error||l)(n):(e.success||l)(e)}function h(t,r,i,c){var s,o,e=document,n=i.async,f=(i.numRetries||0)+1,u=i.before||l,a=t.replace(/^(css|img)!/,"");c=c||0,/(^css!|\.css$)/.test(t)?(s=!0,(o=e.createElement("link")).rel="stylesheet",o.href=a):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(o=e.createElement("img")).src=a:((o=e.createElement("script")).src=t,o.async=void 0===n||n),!(o.onload=o.onerror=o.onbeforeload=function(e){var n=e.type[0];if(s&&"hideFocus"in o)try{o.sheet.cssText.length||(n="e")}catch(e){n="e"}if("e"==n&&(c+=1)<f)return h(t,r,i,c);r(t,n,e.defaultPrevented)})!==u(t,o)&&e.head.appendChild(o)}function t(e,n,t){var r,i;if(n&&n.trim&&(r=n),i=(r?t:n)||{},r){if(r in c)throw"LoadJS";c[r]=!0}!function(e,r,n){var t,i,c=(e=e.push?e:[e]).length,s=c,o=[];for(t=function(e,n,t){if("e"==n&&o.push(e),"b"==n){if(!t)return;o.push(e)}--c||r(o)},i=0;i<s;i++)h(e[i],t,n)}(e,function(e){o(i,e),s(r,e)},i)}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,i,c=[],s=e.length,o=s;for(n=function(e,n){n.length&&c.push(e),--o||t(c)};s--;)r=e[s],(i=f[r])?n(r,i):(u[r]=u[r]||[]).push(n)}(e,function(e){o(n,e)}),t},t.done=function(e){s(e,[])},t.reset=function(){c={},f={},u={}},t.isDefined=function(e){return e in c},t}(); <MSG> bumped version number <DFF> @@ -1,1 +1,1 @@ -loadjs=function(){var l=function(){},c={},f={},u={};function s(e,n){if(e){var t=u[e];if(f[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function o(e,n){e.call&&(e={success:e}),n.length?(e.error||l)(n):(e.success||l)(e)}function h(t,r,i,c){var s,o,e=document,n=i.async,f=(i.numRetries||0)+1,u=i.before||l,a=t.replace(/^(css|img)!/,"");c=c||0,/(^css!|\.css$)/.test(t)?(s=!0,(o=e.createElement("link")).rel="stylesheet",o.href=a):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(o=e.createElement("img")).src=a:((o=e.createElement("script")).src=t,o.async=void 0===n||n),!(o.onload=o.onerror=o.onbeforeload=function(e){var n=e.type[0];if(s&&"hideFocus"in o)try{o.sheet.cssText.length||(n="e")}catch(e){n="e"}if("e"==n&&(c+=1)<f)return h(t,r,i,c);r(t,n,e.defaultPrevented)})!==u(t,o)&&e.head.appendChild(o)}function t(e,n,t){var r,i;if(n&&n.trim&&(r=n),i=(r?t:n)||{},r){if(r in c)throw"LoadJS";c[r]=!0}!function(e,r,n){var t,i,c=(e=e.push?e:[e]).length,s=c,o=[];for(t=function(e,n,t){if("e"==n&&o.push(e),"b"==n){if(!t)return;o.push(e)}--c||r(o)},i=0;i<s;i++)h(e[i],t,n)}(e,function(e){o(i,e),s(r,e)},i)}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,i,c=[],s=e.length,o=s;for(n=function(e,n){n.length&&c.push(e),--o||t(c)};s--;)r=e[s],(i=f[r])?n(r,i):(u[r]=u[r]||[]).push(n)}(e,function(e){o(n,e)}),t},t.done=function(e){s(e,[])},t.reset=function(){c={},f={},u={}},t.isDefined=function(e){return e in c},t}(); \ No newline at end of file +loadjs=function(){var l=function(){},c={},f={},u={};function o(e,n){if(e){var t=u[e];if(f[e]=n,t)for(;t.length;)t[0](e,n),t.splice(0,1)}}function s(e,n){e.call&&(e={success:e}),n.length?(e.error||l)(n):(e.success||l)(e)}function h(t,r,i,c){var o,s,e=document,n=i.async,f=(i.numRetries||0)+1,u=i.before||l,a=t.replace(/^(css|img)!/,"");c=c||0,/(^css!|\.css$)/.test(t)?(o=!0,(s=e.createElement("link")).rel="stylesheet",s.href=a):/(^img!|\.(png|gif|jpg|svg)$)/.test(t)?(s=e.createElement("img")).src=a:((s=e.createElement("script")).src=t,s.async=void 0===n||n),!(s.onload=s.onerror=s.onbeforeload=function(e){var n=e.type[0];if(o&&"hideFocus"in s)try{s.sheet.cssText.length||(n="e")}catch(e){18!=e.code&&(n="e")}if("e"==n&&(c+=1)<f)return h(t,r,i,c);r(t,n,e.defaultPrevented)})!==u(t,s)&&e.head.appendChild(s)}function t(e,n,t){var r,i;if(n&&n.trim&&(r=n),i=(r?t:n)||{},r){if(r in c)throw"LoadJS";c[r]=!0}!function(e,r,n){var t,i,c=(e=e.push?e:[e]).length,o=c,s=[];for(t=function(e,n,t){if("e"==n&&s.push(e),"b"==n){if(!t)return;s.push(e)}--c||r(s)},i=0;i<o;i++)h(e[i],t,n)}(e,function(e){s(i,e),o(r,e)},i)}return t.ready=function(e,n){return function(e,t){e=e.push?e:[e];var n,r,i,c=[],o=e.length,s=o;for(n=function(e,n){n.length&&c.push(e),--s||t(c)};o--;)r=e[o],(i=f[r])?n(r,i):(u[r]=u[r]||[]).push(n)}(e,function(e){s(n,e)}),t},t.done=function(e){o(e,[])},t.reset=function(){c={},f={},u={}},t.isDefined=function(e){return e in c},t}(); \ No newline at end of file
1
bumped version number
1
.js
min
mit
muicss/loadjs
10067413
<NME> README.md <BEF> # FruitMachine [![Build Status](https://api.travis-ci.com/ftlabs/fruitmachine.svg)](https://travis-ci.com/ftlabs/fruitmachine) [![Coverage Status](https://coveralls.io/repos/ftlabs/fruitmachine/badge.png)](https://coveralls.io/r/ftlabs/fruitmachine) A lightweight component layout engine for client and server. FruitMachine is designed to build rich interactive layouts from modular, reusable components. It's light and unopinionated so that it can be applied to almost any layout problem. FruitMachine is currently powering the [FT Web App](http://apps.ft.com/ftwebapp/). ```js // Define a module var Apple = fruitmachine.define({ name: 'apple', template: function(){ return 'hello' } }); // Create a module var apple = new Apple(); // Render it apple.render(); apple.el.outerHTML; //=> <div class="apple">hello</div> ``` ## Installation ``` $ npm install fruitmachine ``` or ``` $ bower install fruitmachine ``` or Download the [pre-built version][built] (~2k gzipped). [built]: http://wzrd.in/standalone/fruitmachine@latest ## Examples - [Article viewer](http://ftlabs.github.io/fruitmachine/examples/article-viewer/) - [TODO](http://ftlabs.github.io/fruitmachine/examples/todo/) ## Documentation - [Introduction](docs/introduction.md) - [Getting started](docs/getting-started.md) - [Defining modules](docs/defining-modules.md) - [Slots](docs/slots.md) - [View assembly](docs/layout-assembly.md) - [Instantiation](docs/module-instantiation.md) - [Templates](docs/templates.md) - [Template markup](docs/template-markup.md) - [Rendering](docs/rendering.md) - [DOM injection](docs/injection.md) - [The module element](docs/module-el.md) - [Queries](docs/queries.md) - [Helpers](docs/module-helpers.md) - [Removing & destroying](docs/removing-and-destroying.md) - [Extending](docs/extending-modules.md) - [Server-side rendering](docs/server-side-rendering.md) - [API](docs/api.md) - [Events](docs/events.md) ## Tests #### With PhantomJS ``` $ npm install $ npm test ``` #### Without PhantomJS ``` $ node_modules/.bin/buster-static ``` ...then visit http://localhost:8282/ in browser ## Author - **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage) ## Contributors - **Wilson Page** - [@wilsonpage](http://github.com/wilsonpage) - **Matt Andrews** - [@matthew-andrews](http://github.com/matthew-andrews) ## License Copyright (c) 2014 The Financial Times Limited Licensed under the MIT license. ## Credits and collaboration The lead developer of FruitMachine is [Wilson Page](http://github.com/wilsonpage) at FT Labs. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request. <MSG> Update README.md <DFF> @@ -92,9 +92,8 @@ $ node_modules/.bin/buster-static - **Matt Andrews** - [@matthew-andrews](http://github.com/matthew-andrews) ## License -Copyright (c) 2014 The Financial Times Limited +Copyright (c) 2018 The Financial Times Limited Licensed under the MIT license. ## Credits and collaboration - -The lead developer of FruitMachine is [Wilson Page](http://github.com/wilsonpage) at FT Labs. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request. +FruitMachine is largely unmaintained/finished. All open source code released by FT Labs is licenced under the MIT licence. We welcome comments, feedback and suggestions. Please feel free to raise an issue or pull request.
2
Update README.md
3
.md
md
mit
ftlabs/fruitmachine
10067414
<NME> fruitmachine.js <BEF> /*jslint browser:true, node:true*/ /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * Options: * * - `Model` A model constructor to use (must have `.toJSON()`) * * @param {Object} options */ module.exports = function(options) { /** * Shortcut method for * creating lazy views. * * @param {Object} options * @return {Module} */ function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); } throw new Error("Unable to find module '" + options.module + "'"); } fm.create = module.exports; fm.Model = options.Model; fm.Events = events; fm.Module = mod(fm); fm.define = define(fm); fm.util = utils; fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; }, wrapHTML: function(html) { return '<' + this.tag + ' class="' + this.module + ' ' + this.classes.join(' ') + '" id="' + this.fmid() + '">' + html + '</div>'; }, purgeHtmlCache: function() { } else { window['FruitMachine'] = FruitMachine; } }()); <MSG> Merge branch 'master' of 10.119.160.180:ftlabs/fruitmachine into 0.2 <DFF> @@ -426,7 +426,7 @@ }, wrapHTML: function(html) { - return '<' + this.tag + ' class="' + this.module + ' ' + this.classes.join(' ') + '" id="' + this.fmid() + '">' + html + '</div>'; + return '<' + this.tag + ' class="' + this.module + ' ' + this.classes.join(' ') + '" id="' + this.fmid() + '">' + html + '</' + this.tag + '>'; }, purgeHtmlCache: function() { @@ -849,4 +849,4 @@ } else { window['FruitMachine'] = FruitMachine; } -}()); \ No newline at end of file +}());
2
Merge branch 'master' of 10.119.160.180:ftlabs/fruitmachine into 0.2
2
.js
js
mit
ftlabs/fruitmachine
10067415
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067416
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067417
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067418
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067419
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067420
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067421
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067422
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067423
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067424
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067425
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067426
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067427
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067428
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067429
<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; } { if (_invalidateMeasureOperation == null) { _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( delegate { _invalidateMeasureOperation = null; 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>(); VisualLineConstructionStarting?.Invoke(this, new VisualLineConstructionStartEventArgs(firstLineInView)); var elementGeneratorsArray = _elementGenerators.ToArray(); var lineTransformersArray = _lineTransformers.ToArray(); var nextLine = firstLineInView; double maxWidth = 0; var yPos = -_clippedPixelsOnTop; while (yPos < availableSize.Height && nextLine != null) { 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)); inline.Element.Arrange(new Rect(new Point(pos.X + distance, pos.Y), inline.Element.DesiredSize)); Debug.WriteLine(distance); } offset += span.TextSourceLength; } pos = new Point(pos.X, pos.Y + textLine.Height); } } } 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() { SetScrollData(new Size(), new Size(), new Vector()); } private bool SetScrollData(Size viewport, Size extent, Vector offset) { if (!(viewport.IsClose(_scrollViewport) && extent.IsClose(_scrollExtent) && offset.IsClose(_scrollOffset))) { _scrollViewport = viewport; _scrollExtent = extent; SetScrollOffset(offset); OnScrollChange(); return true; } 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> update avalonia api. <DFF> @@ -745,7 +745,7 @@ namespace AvaloniaEdit.Rendering { if (_invalidateMeasureOperation == null) { - _invalidateMeasureOperation = Dispatcher.UIThread.InvokeTaskAsync( + _invalidateMeasureOperation = Dispatcher.UIThread.InvokeAsync( delegate { _invalidateMeasureOperation = null;
1
update avalonia api.
1
.cs
cs
mit
AvaloniaUI/AvaloniaEdit
10067430
<NME> module.js <BEF> var Backbone = require('backbone'); describe('View', function() { test("Should add any children passed into the constructor", function() { var children = [ { module: 'pear' }, { module: 'orange' } ]; var view = new fruitmachine({ module: 'apple', children: children }); expect(view.children.length).toBe(2); }); test("Should store a reference to the slot if passed", function() { var view = new fruitmachine({ module: 'apple', children: [ { module: 'pear', slot: 1 }, { module: 'orange', slot: 2 } ] }); expect(view.slots[1]).toBeTruthy(); expect(view.slots[2]).toBeTruthy(); }); test("Should store a reference to the slot if slot is passed as key of children object", function() { var view = new fruitmachine({ module: 'apple', children: { 1: { module: 'pear' }, 2: { module: 'orange' } } }); expect(view.slots[1]).toBeTruthy(); expect(view.slots[2]).toBeTruthy(); }); test("Should store a reference to the slot if the view is instantiated with a slot", function() { var apple = new Apple({ slot: 1 }); expect(apple.slot).toBe(1); }); test("Should prefer the slot on the children object in case of conflict", function() { var apple = new Apple({ slot: 1 }); var layout = new Layout({ children: { 2: apple } }); expect(layout.module('apple').slot).toBe('2'); }); test("Should create a model", function() { var view = new fruitmachine({ module: 'apple' }); expect(view.model instanceof fruitmachine.Model).toBe(true); }); test("Should adopt the fmid if passed", function() { var view = new fruitmachine({ fmid: '1234', module: 'apple' }); expect(view._fmid).toBe('1234'); }); test("Should fire an 'inflation' event on fm instance if instantiated with an fmid", function() { var spy = jest.fn(); fruitmachine.on('inflation', spy); var layout = new fruitmachine({ fmid: '1', module: 'layout', children: { 1: { fmid: '2', module: 'apple' } } }); expect(spy).toHaveBeenCalledTimes(2); }); test("Should fire an 'inflation' event on fm instance with the view as the first arg", function() { var spy = jest.fn(); fruitmachine.on('inflation', spy); var layout = new fruitmachine({ fmid: '1', module: 'layout', children: { 1: { fmid: '2', module: 'apple' } } }); expect(spy.mock.calls[0][0]).toBe(layout); expect(spy.mock.calls[1][0]).toBe(layout.module('apple')); }); test("Should fire an 'inflation' event on fm instance with the options as the second arg", function() { var spy = jest.fn(); var options = { fmid: '1', module: 'layout' }; fruitmachine.on('inflation', spy); var layout = new fruitmachine(options); expect(spy.mock.calls[0][1]).toEqual(options); }); test("Should be able to use Backbone models", function() { var orange = new Orange({ model: new Backbone.Model({ text: 'orange text' }) }); orange.render(); expect(orange.el.innerHTML.indexOf('orange text')).toBe(0); }); test("Should define a global default model", function() { var previous = fruitmachine.Module.prototype.Model; fruitmachine.Module.prototype.Model = Backbone.Model; var orange = new Orange({ model: { text: 'orange text' } }); orange.render(); expect(orange.model instanceof Backbone.Model).toBe(true); expect(orange.el.innerHTML.indexOf('orange text')).toBe(0); // Restore fruitmachine.Module.prototype.Model = previous; }); test("Should define a module default model", function() { var Berry = fruitmachine.define({ name: 'berry', Model: Backbone.Model var berry = new Berry({ model: { foo: 'bar' }}); assert(berry.model instanceof Backbone.Model); } }); }); }); <MSG> Failing test to cover the potential bugs caused by only shallow-cloning the options object <DFF> @@ -164,5 +164,16 @@ buster.testCase('View', { var berry = new Berry({ model: { foo: 'bar' }}); assert(berry.model instanceof Backbone.Model); + }, + + "// Should not modify the options object": function() { + var options = { + classes: ['my class'] + }; + + var orange = new Orange(options); + orange.classes.push('added'); + + assert.equals(['my class'], options.classes); } }); \ No newline at end of file
11
Failing test to cover the potential bugs caused by only shallow-cloning the options object
0
.js
js
mit
ftlabs/fruitmachine
10067431
<NME> fruitmachine.js <BEF> /*jslint browser:true, node:true*/ /** * FruitMachine * * Renders layouts/modules from a basic layout definition. * If views require custom interactions devs can extend * the basic functionality. * * @version 0.3.3 * @copyright The Financial Times Limited [All Rights Reserved] * @author Wilson Page <[email protected]> */ 'use strict'; /** * Module Dependencies */ var mod = require('./module'); var define = require('./define'); var utils = require('utils'); var events = require('evt'); /** * Creates a fruitmachine * * Options: * * - `Model` A model constructor to use (must have `.toJSON()`) * * @param {Object} options */ module.exports = function(options) { /** * Shortcut method for * creating lazy views. * * @param {Object} options * @return {Module} */ function fm(options) { var Module = fm.modules[options.module]; if (Module) { return new Module(options); } throw new Error("Unable to find module '" + options.module + "'"); } fm.create = module.exports; fm.Model = options.Model; fm.Events = events; fm.Module = mod(fm); fm.define = define(fm); fm.util = utils; fm.modules = {}; fm.config = { templateIterator: 'children', templateInstance: 'child' }; // Mixin events and return return events(fm); }; this.model = options.model || new Model(options.data || {}); // Purge html caches when the model is changed this.model.on('change', util.bind(this.purgeHtmlCache, this)); // Init named helpers (this.helpers || []).forEach(function(helper) { 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 return this; }, addLookup: function(child) { this._lookup[child.id()] = child; this._lookup[child.module] = this._lookup[child.module] || []; this._lookup[child.module].push(child); }, injectElement: function(el, options) { var at = options && options.at; var parent = this.el; toHTML: function() { var data = {}; var html; data.children = []; // Use cache if populated if (this.html) return this.html; // Loop each child this.each(function(child) { html = child.toHTML(); data.children.push(mixin({ child: html }, child.model.get())); }); html = this.template(mixin(data, this.model.get())); return this.html = this.wrapHTML(html); }, }, purgeHtmlCache: function() { if (!this.html) return; this.html = null; if (this.parent) this.parent.purgeHtmlCache(); return this; }, // Overwrite this if you want render: function() { var el = this.toNode(); this.setElement(el); this.trigger('render'); return this; }, * * @return {View} */ empty: function() { var children = this.children(); while (children.length) children[0].destroy(); return this; }, // variables if setup hasn't run. if (!this.isSetup) return this; // Clear the el cache this.clearElement(); this.trigger('teardown'); this.onTeardown(); this.isSetup = false; }, destroy: function(options) { // Recursively run on views // 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({ remove: false }); } // 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(); // Unbind any old event listeners this.off(); this.destroyed = true; // Clear references this.model = this.parent = this._lookup = this.module = this._id = null; }, /** * * @return {FruitMachine} */ remove: function() { var el = this.el; if (el && el.parentNode) el.parentNode.removeChild(el); return this; }, _detach: function(options) { var remove = options && options.skipEl; var i; // Remove the view el from the DOM if (remove !== false) this.remove(); // If there is no parent view reference, return here. if (!this.parent) return this; // Remove reference from views array i = this.parent._children.indexOf(this); this.parent._children.splice(i, 1); // Remove references from the lookup i = this.parent._lookup[this.module].indexOf(this); this.parent._lookup[this.module].splice(i, 1); delete this.parent._lookup[this._id]; // Return the detached view instance. return this; }, closestElement: function() { var view = this.parent; while (view && !view.el && view.parent) view = view.parent; return view && view.el; }, getElement: function() { if (!hasDom) return; return this.el = this.el || this.parent && util.querySelectorId(this._fmid, this.closestElement()); }, setElement: function(el) { var existing = this.el; return this; }, clearElement: function() { this.el = null; }, purgeElementCaches: function() { this.each(function(child) { child.purgeElementCaches(); }); this.clearElement(); }, /** * @param {*} value * @return {*} */ data: function(key, value) { // If no key and no value have } }, inDOM: function() { if (this.parent) return this.parent.inDOM(); return !!(this.el && this.el.parentNode); }, toNode: function() { var el = document.createElement('div'); el.innerHTML = this.toHTML(); return el.removeChild(el.firstElementChild); }, inject: function(dest) { if (!this.el) return; dest.innerHTML = ''; dest.appendChild(this.el); return this; }, appendTo: function(dest) { if (!this.el) return; dest.appendChild(this.el); return this; }, toJSON: function() { var json = {}; json.children = []; <MSG> Fine tuning View#destroy() with some tests <DFF> @@ -322,7 +322,8 @@ this.model = options.model || new Model(options.data || {}); // Purge html caches when the model is changed - this.model.on('change', util.bind(this.purgeHtmlCache, this)); + this.purgeHtmlCache = util.bind(this.purgeHtmlCache, this); + this.model.on('change', this.purgeHtmlCache); // Init named helpers (this.helpers || []).forEach(function(helper) { @@ -359,7 +360,7 @@ if (!(child instanceof View)) child = new View(child); util.insert(child, this._children, at); - this.addLookup(child); + this._addLookup(child); child.parent = this; // We append the child to the parent view if there is a view @@ -372,12 +373,18 @@ return this; }, - addLookup: function(child) { + _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; @@ -485,11 +492,14 @@ toHTML: function() { var data = {}; var html; - data.children = []; // 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(); @@ -497,8 +507,14 @@ 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); }, @@ -507,17 +523,31 @@ }, purgeHtmlCache: function() { - if (!this.html) return; + + // Clear html this.html = null; + + // Recurse if (this.parent) this.parent.purgeHtmlCache(); + return this; }, - // Overwrite this if you want 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'); + return this; }, @@ -526,10 +556,12 @@ * * @return {View} */ - empty: function() { var children = this.children(); - while (children.length) children[0].destroy(); + var l = children.length; + + while (l--) children[l].destroy(); + return this; }, @@ -586,9 +618,6 @@ // variables if setup hasn't run. if (!this.isSetup) return this; - // Clear the el cache - this.clearElement(); - this.trigger('teardown'); this.onTeardown(); this.isSetup = false; @@ -598,32 +627,46 @@ }, destroy: function(options) { + var children = this._children; + var l = children.length; - // Recursively run on views - // first (bottom up). - // + // Destroy each child view. // 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({ remove: false }); + // + // 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 }); } - // Run teardown so custom - // views can bind logic to it - this.teardown(options); + // 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._detach(options); + 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'); 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(); @@ -635,7 +678,7 @@ this.destroyed = true; // Clear references - this.model = this.parent = this._lookup = this.module = this._id = null; + this.el = this.model = this.parent = this._lookup = this.module = this._id = null; }, /** @@ -644,41 +687,56 @@ * * @return {FruitMachine} */ - remove: function() { + remove: function(options) { + options = options || {}; var el = this.el; - if (el && el.parentNode) el.parentNode.removeChild(el); - return this; - }, - - _detach: function(options) { - var remove = options && options.skipEl; - var i; + var index; - // Remove the view el from the DOM - if (remove !== false) this.remove(); + // 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 there is no parent view + // reference, return here. if (!this.parent) return this; // Remove reference from views array - i = this.parent._children.indexOf(this); - this.parent._children.splice(i, 1); + index = this.parent._children.indexOf(this); + this.parent._children.splice(index, 1); // Remove references from the lookup - i = this.parent._lookup[this.module].indexOf(this); - this.parent._lookup[this.module].splice(i, 1); - delete this.parent._lookup[this._id]; + this.parent._removeLookup(this); - // Return the detached view instance. 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 @@ -686,6 +744,19 @@ || 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; @@ -702,16 +773,18 @@ return this; }, - clearElement: function() { - this.el = null; - }, - + /** + * Recursively purges the + * element cache. + * + * @return void + */ purgeElementCaches: function() { this.each(function(child) { child.purgeElementCaches(); }); - this.clearElement(); + this.el = null; }, /** @@ -735,7 +808,6 @@ * @param {*} value * @return {*} */ - data: function(key, value) { // If no key and no value have @@ -767,30 +839,70 @@ } }, + /** + * 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 (!this.el) return; - dest.innerHTML = ''; - dest.appendChild(this.el); + 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) return; - dest.appendChild(this.el); + 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 = [];
161
Fine tuning View#destroy() with some tests
49
.js
js
mit
ftlabs/fruitmachine
10067432
<NME> jsgrid.field.js <BEF> (function(jsGrid, $, undefined) { function Field(config) { $.extend(true, this, config); this.sortingFunc = this._getSortingFunc(); } Field.prototype = { name: "", title: null, css: "", align: "", width: 100, visible: true, filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", // name of SortStrategy or function to compare elements headerTemplate: function() { return (this.title === undefined || this.title === null) ? this.name : this.title; }, itemTemplate: function(value, item) { return value; }, filterTemplate: function() { return ""; }, insertTemplate: function() { return ""; }, editTemplate: function(value, item) { this._value = value; return this.itemTemplate(value, item); }, filterValue: function() { return ""; }, insertValue: function() { return ""; }, editValue: function() { return this._value; }, _getSortingFunc: function() { var sorter = this.sorter; if($.isFunction(sorter)) { return sorter; } if(typeof sorter === "string") { return jsGrid.sortStrategies[sorter]; } throw Error("wrong sorter for the field \"" + this.name + "\"!"); } }; jsGrid.Field = Field; }(jsGrid, jQuery)); <MSG> Core: Added initial Data Export feature. Fields: Added default configs to support the Data Exporting functions <DFF> @@ -18,6 +18,8 @@ editing: true, sorting: true, sorter: "string", // name of SortStrategy or function to compare elements + + includeInDataExport: true, headerTemplate: function() { return (this.title === undefined || this.title === null) ? this.name : this.title;
2
Core: Added initial Data Export feature. Fields: Added default configs to support the Data Exporting functions
0
.js
field
mit
tabalinas/jsgrid
10067433
<NME> jsgrid.field.js <BEF> (function(jsGrid, $, undefined) { function Field(config) { $.extend(true, this, config); this.sortingFunc = this._getSortingFunc(); } Field.prototype = { name: "", title: null, css: "", align: "", width: 100, visible: true, filtering: true, inserting: true, editing: true, sorting: true, sorter: "string", // name of SortStrategy or function to compare elements headerTemplate: function() { return (this.title === undefined || this.title === null) ? this.name : this.title; }, itemTemplate: function(value, item) { return value; }, filterTemplate: function() { return ""; }, insertTemplate: function() { return ""; }, editTemplate: function(value, item) { this._value = value; return this.itemTemplate(value, item); }, filterValue: function() { return ""; }, insertValue: function() { return ""; }, editValue: function() { return this._value; }, _getSortingFunc: function() { var sorter = this.sorter; if($.isFunction(sorter)) { return sorter; } if(typeof sorter === "string") { return jsGrid.sortStrategies[sorter]; } throw Error("wrong sorter for the field \"" + this.name + "\"!"); } }; jsGrid.Field = Field; }(jsGrid, jQuery)); <MSG> Core: Added initial Data Export feature. Fields: Added default configs to support the Data Exporting functions <DFF> @@ -18,6 +18,8 @@ editing: true, sorting: true, sorter: "string", // name of SortStrategy or function to compare elements + + includeInDataExport: true, headerTemplate: function() { return (this.title === undefined || this.title === null) ? this.name : this.title;
2
Core: Added initial Data Export feature. Fields: Added default configs to support the Data Exporting functions
0
.js
field
mit
tabalinas/jsgrid
10067434
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067435
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067436
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067437
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067438
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067439
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067440
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067441
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067442
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067443
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067444
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067445
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067446
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067447
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067448
<NME> TextEditorModelTests.cs <BEF> ο»Ώusing AvaloniaEdit.Document; using AvaloniaEdit.Rendering; using AvaloniaEdit.TextMate; using NUnit.Framework; namespace AvaloniaEdit.Tests.TextMate { [TestFixture] internal class TextEditorModelTests { [Test] public void Lines_Should_Have_Valid_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); } [Test] public void Lines_Should_Have_Valid_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } [Test] public void Editing_Line_Should_Update_The_Line_Length() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); } [Test] public void Inserting_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } [Test] public void Removing_Line_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Removing_Line_With_LFCR_Should_Update_The_Line_Ranges() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\r\npussy\r\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } [Test] public void Document_Lines_Count_Should_Match_Model_Lines_Count() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Edit_Document_Line_Should_Not_Add_Or_Remove_Model_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "cutty "); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Insert_Document_Line_Should_Insert_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Insert(0, "lion\n"); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Remove_Document_Line_Should_Remove_Model_Line() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Remove( document.Lines[0].Offset, document.Lines[0].TotalLength); int count = 0; textEditorModel.ForEach((m) => count++); Assert.AreEqual(document.LineCount, count); } [Test] public void Replace_Text_Of_Same_Length_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "P"); Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); } [Test] public void Replace_Text_Of_Same_Length_With_CR_Should_Update_Line_Content() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; document.Replace(0, 1, "\n"); Assert.AreEqual("\n", textEditorModel.GetLineText(0)); } } } public void Remove_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = string.Empty; Assert.AreEqual(1, textEditorModel.GetNumberOfLines()); Assert.AreEqual(string.Empty, textEditorModel.GetLineText(0)); } [Test] public void Replace_Document_Text_Should_Update_Line_Contents() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npussy\nbirdie"; Assert.AreEqual(3, textEditorModel.GetNumberOfLines()); document.Text = "one\ntwo\nthree\nfour"; Assert.AreEqual(4, textEditorModel.GetNumberOfLines()); Assert.AreEqual("one", textEditorModel.GetLineText(0)); Assert.AreEqual("two", textEditorModel.GetLineText(1)); Assert.AreEqual("three", textEditorModel.GetLineText(2)); Assert.AreEqual("four", textEditorModel.GetLineText(3)); } [Test] public void Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } [Test] public void Nested_Batch_Document_Changes_Should_Invalidate_Lines() { TextView textView = new TextView(); TextDocument document = new TextDocument(); using var textEditorModel = new TextEditorModel( textView, document, null); document.Text = "puppy\npuppy\npuppy"; document.BeginUpdate(); document.Insert(0, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 1"); Assert.AreEqual(0, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 1"); document.BeginUpdate(); document.Insert(7, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 2"); Assert.AreEqual(1, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 2"); document.Insert(14, "*"); Assert.AreEqual(0, textEditorModel.InvalidRange.StartLine, "Wrong InvalidRange.StartLine 3"); Assert.AreEqual(2, textEditorModel.InvalidRange.EndLine, "Wrong InvalidRange.EndLine 3"); document.EndUpdate(); Assert.IsNotNull(textEditorModel.InvalidRange, "InvalidRange should not be null"); document.EndUpdate(); Assert.IsNull(textEditorModel.InvalidRange, "InvalidRange should be null"); Assert.AreEqual("*puppy", textEditorModel.GetLineText(0)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(1)); Assert.AreEqual("*puppy", textEditorModel.GetLineText(2)); } } } <MSG> Fixed unit tests Now the text editor model doesn't retrieve the line terminators <DFF> @@ -34,8 +34,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Text = "puppy\npussy\nbirdie"; - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -52,8 +52,8 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(1)); + Assert.AreEqual("cutty puppy", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(1)); Assert.AreEqual("birdie", textEditorModel.GetLineText(2)); } @@ -70,7 +70,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "cutty "); - Assert.AreEqual("cutty puppy\n".Length, textEditorModel.GetLineLength(0)); + Assert.AreEqual("cutty puppy".Length, textEditorModel.GetLineLength(0)); } [Test] @@ -86,9 +86,9 @@ namespace AvaloniaEdit.Tests.TextMate document.Insert(0, "lion\n"); - Assert.AreEqual("lion\n", textEditorModel.GetLineText(0)); - Assert.AreEqual("puppy\n", textEditorModel.GetLineText(1)); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(2)); + Assert.AreEqual("lion", textEditorModel.GetLineText(0)); + Assert.AreEqual("puppy", textEditorModel.GetLineText(1)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(2)); Assert.AreEqual("birdie", textEditorModel.GetLineText(3)); } @@ -107,7 +107,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -126,7 +126,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Lines[0].Offset, document.Lines[0].TotalLength); - Assert.AreEqual("pussy\r\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("pussy", textEditorModel.GetLineText(0)); Assert.AreEqual("birdie", textEditorModel.GetLineText(1)); } @@ -219,7 +219,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "P"); - Assert.AreEqual("Puppy\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("Puppy", textEditorModel.GetLineText(0)); } [Test] @@ -235,7 +235,7 @@ namespace AvaloniaEdit.Tests.TextMate document.Replace(0, 1, "\n"); - Assert.AreEqual("\n", textEditorModel.GetLineText(0)); + Assert.AreEqual("", textEditorModel.GetLineText(0)); } } }
12
Fixed unit tests
12
.cs
Tests/TextMate/TextEditorModelTests
mit
AvaloniaUI/AvaloniaEdit
10067449
<NME> README.md <BEF> # LoadJS <img src="https://www.muicss.com/static/images/loadjs.svg" width="30%"> LoadJS is a tiny async loading library for the browser. [![Build Status](https://travis-ci.org/muicss/loadjs.svg?branch=master)](https://travis-ci.org/muicss/loadjs) [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) [![CDNJS](https://img.shields.io/cdnjs/v/loadjs.svg)](https://cdnjs.com/libraries/loadjs) ## Introduction LoadJS is a tiny async loading library for modern browsers (IE9+). It has a simple yet powerful dependency management system that lets you fetch JavaScript, CSS and image files in parallel and execute code after the dependencies have been met. The recommended way to use LoadJS is to include the minified source code of [loadjs.js](https://raw.githubusercontent.com/muicss/loadjs/master/dist/loadjs.min.js) in your &lt;html&gt; (possibly in the &lt;head&gt; tag) and then use the `loadjs` global to manage JavaScript dependencies after pageload. LoadJS is based on the excellent [$script](https://github.com/ded/script.js) library by [Dustin Diaz](https://github.com/ded). We kept the behavior of the library the same but we re-wrote the code from scratch to add support for success/error callbacks and to optimize the library for modern browsers. LoadJS is 899 bytes (minified + gzipped). Here's an example of what you can do with LoadJS: ```html <script src="//unpkg.com/loadjs@latest/dist/loadjs.min.js"></script> <script> // define a dependency bundle and execute code when it loads loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { β”œβ”€β”€ test/ </pre> ## Dependencies * nodejs (http://nodejs.org/) * npm (https://www.npmjs.org/) ## Documentation // define a dependency bundle with advanced options loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { before: function(path, scriptEl) { /* execute code before fetch */ }, async: true, // load files synchronously or asynchronously (default: true) numRetries: 3 // see caveats about using numRetries with async:false (default: 0), returnPromise: false // return Promise object (default: false) }); loadjs.ready('foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(depsNotFound) { /* foobar bundle load failed */ }, }); </script> ``` The latest version of LoadJS can be found in the `dist/` directory in this repository: * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.js) (for development) * [https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js](https://cdn.rawgit.com/muicss/loadjs/4.2.0/dist/loadjs.min.js) (for production) It's also available from these public CDNs: * UNPKG * [https://unpkg.com/[email protected]/dist/loadjs.js](https://unpkg.com/[email protected]/dist/loadjs.js) (for development) * [https://unpkg.com/[email protected]/dist/loadjs.min.js](https://unpkg.com/[email protected]/dist/loadjs.min.js) (for production) * CDNJS * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.js) (for development) * [https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js](https://cdnjs.cloudflare.com/ajax/libs/loadjs/4.2.0/loadjs.min.js) (for production) You can also use it as a CJS or AMD module: ```bash $ npm install --save loadjs ``` ```javascript var loadjs = require('loadjs'); loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` ## Browser Support * IE9+ (`async: false` support only works in IE10+) * Opera 12+ * Safari 5+ * Chrome * Firefox * iOS 6+ * Android 4.4+ LoadJS also detects script load failures from AdBlock Plus and Ghostery in: * Safari * Chrome Note: LoadJS treats empty CSS files as load failures in IE9-11 and uses `rel="preload"` to load CSS files in Edge (to get around lack of support for onerror events on `<link rel="stylesheet">` tags) ## Documentation 1. Load a single file ```javascript loadjs('/path/to/foo.js', function() { /* foo.js loaded */ }); ``` 1. Fetch files in parallel and load them asynchronously ```javascript // run code here when jquery and my awesome plugin are both finished }) ``` loadjs(['/path/to/foo.css', '/path/to/bar.png', 'path/to/thunk.js'], function() { /* foo.css, bar.png and thunk.js loaded */ }); ``` 1. Force treat file as CSS stylesheet ```javascript loadjs(['css!/path/to/cssfile.custom'], function() { /* cssfile.custom loaded as stylesheet */ }); ``` 1. Force treat file as image ```javascript loadjs(['img!/path/to/image.custom'], function() { /* image.custom loaded */ }); ``` 1. Add a bundle id ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use .ready() to define bundles and callbacks separately ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar'); loadjs.ready('foobar', function() { /* foo.js & bar.js loaded */ }); ``` 1. Use multiple bundles in .ready() dependency lists ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs(['/path/to/bar1.js', '/path/to/bar2.js'], 'bar'); loadjs.ready(['foo', 'bar'], function() { /* foo.js & bar1.js & bar2.js loaded */ }); ``` 1. Chain .ready() together ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs .ready('foo', function() { /* foo.js loaded */ }) .ready('bar', function() { /* bar.js loaded */ }); ``` 1. Use Promises to register callbacks ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], {returnPromise: true}) .then(function() { /* foo.js & bar.js loaded */ }) .catch(function(pathsNotFound) { /* at least one didn't load */ }); ``` 1. Check if bundle has already been defined ```javascript if (!loadjs.isDefined('foobar')) { loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', function() { /* foo.js & bar.js loaded */ }); } ``` 1. Fetch files in parallel and load them in series ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() { /* foo.js and bar.js loaded in series */ }, async: false }); ``` 1. Add an error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ } }); ``` 1. Retry files before calling the error callback ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], 'foobar', { success: function() { /* foo.js & bar.js loaded */ }, error: function(pathsNotFound) { /* at least one path didn't load */ }, numRetries: 3 }); // NOTE: Using `numRetries` with `async: false` can cause files to load out-of-sync on retries ``` 1. Execute a callback before script tags are embedded ```javascript loadjs(['/path/to/foo.js', '/path/to/bar.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { /* called for each script node before being embedded */ if (path === '/path/to/foo.js') scriptEl.crossOrigin = true; } }); ``` 1. Bypass LoadJS default DOM insertion mechanism (DOM `<head>`) ```javascript loadjs(['/path/to/foo.js'], { success: function() {}, error: function(pathsNotFound) {}, before: function(path, scriptEl) { document.body.appendChild(scriptEl); /* return `false` to bypass default DOM insertion mechanism */ return false; } }); ``` 1. Use bundle ids in error callback ```javascript loadjs('/path/to/foo.js', 'foo'); loadjs('/path/to/bar.js', 'bar'); loadjs(['/path/to/thunkor.js', '/path/to/thunky.js'], 'thunk'); // wait for multiple depdendencies loadjs.ready(['foo', 'bar', 'thunk'], { success: function() { // foo.js & bar.js & thunkor.js & thunky.js loaded }, error: function(depsNotFound) { if (depsNotFound.indexOf('foo') > -1) {}; // foo failed if (depsNotFound.indexOf('bar') > -1) {}; // bar failed if (depsNotFound.indexOf('thunk') > -1) {}; // thunk failed } }); ``` 1. Use .done() for more control ```javascript loadjs.ready(['dependency1', 'dependency2'], function() { /* run code after dependencies have been met */ }); function fn1() { loadjs.done('dependency1'); } function fn2() { loadjs.done('dependency2'); } ``` 1. Reset dependency trackers ```javascript loadjs.reset(); ``` 1. Implement a require-like dependency manager ```javascript var bundles = { 'bundleA': ['/file1.js', '/file2.js'], 'bundleB': ['/file3.js', '/file4.js'] }; function require(bundleIds, callbackFn) { bundleIds.forEach(function(bundleId) { if (!loadjs.isDefined(bundleId)) loadjs(bundles[bundleId], bundleId); }); loadjs.ready(bundleIds, callbackFn); } require(['bundleA'], function() { /* bundleA loaded */ }); require(['bundleB'], function() { /* bundleB loaded */ }); require(['bundleA', 'bundleB'], function() { /* bundleA and bundleB loaded */ }); ``` ## Directory structure <pre> loadjs/ β”œβ”€β”€ dist β”‚Β Β  β”œβ”€β”€ loadjs.js β”‚Β Β  β”œβ”€β”€ loadjs.min.js β”‚Β Β  └── loadjs.umd.js β”œβ”€β”€ examples β”œβ”€β”€ gulpfile.js β”œβ”€β”€ LICENSE.txt β”œβ”€β”€ package.json β”œβ”€β”€ README.md β”œβ”€β”€ src β”‚Β Β  └── loadjs.js β”œβ”€β”€ test └── umd-templates </pre> ## Development Quickstart 1. Install dependencies * [nodejs](http://nodejs.org/) * [npm](https://www.npmjs.org/) * http-server (via npm) 1. Clone repository ```bash $ git clone [email protected]:muicss/loadjs.git $ cd loadjs ``` 1. Install node dependencies using npm ```bash $ npm install ``` 1. Build examples ```bash $ npm run build-examples ``` To view the examples you can use any static file server. To use the `nodejs` http-server module: ```bash $ npm install http-server $ npm run http-server -- -p 3000 ``` Then visit [http://localhost:3000/examples](http://localhost:3000/examples) 1. Build distribution files ```bash $ npm run build-dist ``` The files will be located in the `dist` directory. 1. Run tests To run the browser tests first build the `loadjs` library: ```bash $ npm run build-tests ``` Then visit [http://localhost:3000/test](http://localhost:3000/test) 1. Build all files ```bash $ npm run build-all ``` <MSG> Update README.md <DFF> @@ -2,7 +2,7 @@ <img src="https://www.muicss.com/static/images/loadjs.svg" width="30%"> -LoadJS is a tiny async loading library for the browser. +LoadJS is a tiny async loader for modern browsers (590 B gzipped). [![Build Status](https://travis-ci.org/muicss/loadjs.svg?branch=master)](https://travis-ci.org/muicss/loadjs) [![Dependency Status](https://david-dm.org/muicss/loadjs.svg)](https://david-dm.org/muicss/loadjs) @@ -26,10 +26,9 @@ loadjs/ β”œβ”€β”€ test/ </pre> -## Dependencies +## Introduction + - * nodejs (http://nodejs.org/) - * npm (https://www.npmjs.org/) ## Documentation @@ -110,3 +109,8 @@ loadjs.ready('my-awesome-plugin', function() { // run code here when jquery and my awesome plugin are both finished }) ``` + +## Development Dependencies + + * nodejs (http://nodejs.org/) + * npm (https://www.npmjs.org/)
8
Update README.md
4
.md
md
mit
muicss/loadjs