aboutsummaryrefslogtreecommitdiffstats
path: root/Software/Visual_Studio/MachineStudio/Modules/Tango.MachineStudio.ActionLogs/Views/MainView.xaml
blob: e2d65d7a321fc047d7751d8cccda1065db8106a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
<UserControl x:Class="Tango.MachineStudio.ActionLogs.Views.MainView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             xmlns:mahapps="http://metro.mahapps.com/winfx/xaml/controls"
             xmlns:local="clr-namespace:Tango.MachineStudio.ActionLogs.Views"
             xmlns:sharedConverters="clr-namespace:Tango.SharedUI.Converters;assembly=Tango.SharedUI"
             xmlns:controls="clr-namespace:Tango.SharedUI.Controls;assembly=Tango.SharedUI"
             xmlns:vm="clr-namespace:Tango.MachineStudio.ActionLogs.ViewModels"
             xmlns:global="clr-namespace:Tango.MachineStudio.ActionLogs"
             xmlns:materialDesign="http://materialdesigninxaml.net/winfx/xaml/themes"
             xmlns:wpf="clr-namespace:MaterialDesignThemes.Wpf;assembly=MaterialDesignThemes.Wpf"
             xmlns:diff="clr-namespace:Tango.BL.ValueObjects;assembly=Tango.BL"
             mc:Ignorable="d" 
             d:DesignHeight="1080" d:DesignWidth="1920" Background="Transparent" d:DataContext="{d:DesignInstance Type=vm:MainViewVM, IsDesignTimeCreatable=False}" DataContext="{x:Static global:ViewModelLocator.MainViewVM}">
    <UserControl.Resources>
        <sharedConverters:BooleanToVisibilityConverter x:Key="BooleanToVisibilityConverter" />
        <sharedConverters:EnumToDescriptionConverter x:Key="EnumToDescriptionConverter" />
        <sharedConverters:DateTimeUTCToShortDateTimeConverter x:Key="DateTimeUTCToShortDateTimeConverter"/>
    </UserControl.Resources>
    <Grid IsEnabled="{Binding IsFree}">
        <Grid.RowDefinitions>
            <RowDefinition Height="200"/>
            <RowDefinition Height="1*"/>
        </Grid.RowDefinitions>
        <Grid Margin="40">
            <StackPanel Orientation="Horizontal">
                <Image Source="../Images/actionlogs_title.png" RenderOptions.BitmapScalingMode="Fant"></Image>
                <StackPanel Margin="20 0 0 0" VerticalAlignment="Center">
                    <TextBlock FontSize="50">Action Logs</TextBlock>
                    <TextBlock>Select start/end dates and action log types to trace system changes.</TextBlock>
                </StackPanel>
            </StackPanel>
        </Grid>
        <Grid Grid.Row="1" Margin="40 0 40 40">
            <Grid.RowDefinitions>
                <RowDefinition Height="70"/>
                <RowDefinition Height="1*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition  Width ="7*"/>
                <ColumnDefinition  Width ="3*"/>
            </Grid.ColumnDefinitions >

            <Grid x:Name ="searchButtons" Grid.Row="0" Grid.Column="0" VerticalAlignment="Center" HorizontalAlignment="Stretch">
                <Border Padding="14 14 12 14" BorderBrush="DimGray" BorderThickness="0" Background="{StaticResource Logging.Background}" HorizontalAlignment="Stretch" CornerRadius="2" >
                    <Border.Effect>
                        <DropShadowEffect ShadowDepth="4" BlurRadius="10" Opacity="0.5"/>
                    </Border.Effect>
                    <DockPanel>
                        <StackPanel HorizontalAlignment="Stretch" VerticalAlignment="Stretch" Orientation="Horizontal">
                            <StackPanel  >
                                <TextBlock FontSize="10">Start Date:</TextBlock>
                                <DatePicker x:Name="startdatePicker" SelectedDate="{Binding StartSelectedDate}"   materialDesign:HintAssist.Hint="Pick start date"  Width="160" VerticalAlignment="Center" FontSize="16" />
                            </StackPanel>
                            <StackPanel   Margin="50 0 0 0">
                                <TextBlock FontSize="10">End Date:</TextBlock>
                                <DatePicker x:Name="endDatePicker"  SelectedDate="{Binding EndSelectedDate}" materialDesign:HintAssist.Hint="Pick end date"  Width="160" VerticalAlignment="Center" FontSize="16" />
                            </StackPanel>
                            <DockPanel  Margin="50 0 0 0" >
                                <TextBlock DockPanel.Dock="Top" Text="Action Log Type:" VerticalAlignment="Center" FontSize="10"></TextBlock>
                                <ToggleButton Width="200" Margin="0 5 0 0" x:Name="selectActionsButton">
                                    <ToggleButton.Template>
                                        <ControlTemplate>
                                            <Grid>
                                                <Border CornerRadius="3" BorderBrush="{StaticResource borderBrush}" BorderThickness="1" TextElement.Foreground="Black" >
                                                    <DockPanel>
                                                        <Button Width="18" Padding="0" Height="16" DockPanel.Dock="Right" BorderBrush="{x:Null}" HorizontalAlignment="Left" Click="Button_Click" Style="{StaticResource MaterialDesignFlatButton}" Foreground="{StaticResource MainWindow.Foreground}">
                                                            <materialDesign:PackIcon Width="16"  Height="16"  Kind="ChevronDown" VerticalAlignment="Center" Foreground="{StaticResource MainWindow.Foreground}" HorizontalAlignment="Right"/>
                                                        </Button>
                                                        <TextBlock VerticalAlignment="Center"  Foreground="{StaticResource MainWindow.Foreground}">
                                                         <Run Text="  Select Actions"></Run>
                                                         <Run>(</Run><Run Text="{Binding SelectedActionLogTypes.SynchedSource.Count,Mode=OneWay}"></Run><Run>)</Run>
                                                        </TextBlock>
                                                    </DockPanel>
                                                </Border>
                                                <Popup StaysOpen="False" IsOpen="{Binding RelativeSource={RelativeSource AncestorType=ToggleButton},Path=IsChecked }" >
                                                    <Border Padding="5" Background="{DynamicResource ComboBox.Floating.Background}" BorderBrush="{StaticResource AutoCompleteTextBox.Popup.BorderBrush}">
                                                        <ScrollViewer MaxHeight="600" Background="{DynamicResource ComboBox.Floating.Background}">
                                                            <ItemsControl ItemsSource="{Binding SelectedActionLogTypes}"  Foreground="{StaticResource MainWindow.Foreground}">
                                                                <ItemsControl.ItemTemplate>
                                                                    <DataTemplate>
                                                                        <DockPanel Margin="2">
                                                                            <CheckBox VerticalAlignment="Center" DockPanel.Dock="Left" IsChecked="{Binding IsSelected}" >
                                                                                <TextBlock Margin="5 0 0 0" VerticalAlignment="Center" Text="{Binding Data,Converter={StaticResource EnumToDescriptionConverter}}"></TextBlock>
                                                                            </CheckBox>
                                                                        </DockPanel>
                                                                    </DataTemplate>
                                                                </ItemsControl.ItemTemplate>
                                                            </ItemsControl>
                                                        </ScrollViewer>
                                                    </Border>
                                                </Popup>
                                            </Grid>
                                        </ControlTemplate>
                                    </ToggleButton.Template>
                                </ToggleButton>

                            </DockPanel>
                            <StackPanel Orientation="Horizontal" HorizontalAlignment="Right" VerticalAlignment="Center" Margin="50 10 0 0">
                                <materialDesign:PackIcon Kind="Magnify" Width="26" Height="26"/>
                                <TextBox Width="Auto" materialDesign:HintAssist.Hint="Search by ID, user, related object name" Text="{Binding SearchFilter,UpdateSourceTrigger=PropertyChanged}" />
                            </StackPanel>
                        </StackPanel>
                        <Button DockPanel.Dock="Right" Width="120" HorizontalAlignment="Right"  Command="{Binding SearchCommand}" Margin="10 0 10 0" VerticalAlignment="Center">Search</Button>
                    </DockPanel>
                </Border>
            </Grid>

            <Grid IsEnabled="{Binding IsFree}" Grid.Row="1" Grid.Column="0" HorizontalAlignment="Stretch" VerticalAlignment="Stretch" >
                <DataGrid  Margin="0 0 0 10" SelectionMode="Single" SelectionUnit="FullRow" RowHeight="40" BorderBrush="{StaticResource borderBrush}" IsReadOnly="True" BorderThickness="1" 
                           Background="{StaticResource TransparentBackgroundBrush}"  AlternatingRowBackground="{StaticResource Transparent200}" AutoGenerateColumns="False" CanUserReorderColumns="True"
                           CanUserAddRows="False" CanUserDeleteRows="False" ItemsSource="{Binding ActionLogs}" 
                           SelectedItem="{Binding SelectedActionLog}" HorizontalAlignment="Stretch" HorizontalContentAlignment="Stretch" FontSize="11">
                    <DataGrid.CellStyle>
                        <Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}">
                            <Setter Property="BorderThickness" Value="0"/>
                            <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
                            <Setter Property="VerticalContentAlignment" Value="Center"></Setter>
                            <Style.Triggers>
                                <Trigger Property="IsSelected" Value="True">
                                    <Setter Property="Background" Value="Transparent"></Setter>
                                    <Setter Property="Foreground" Value="{StaticResource AccentColorBrush}" />
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </DataGrid.CellStyle>
                    <DataGrid.RowStyle>
                        <Style TargetType="DataGridRow" BasedOn="{StaticResource {x:Type DataGridRow}}">
                            <Style.Triggers>
                                <Trigger Property="IsMouseOver" Value="True">
                                    <Setter Property="Background" Value="Transparent"></Setter>
                                    <Setter Property="Foreground" Value="{StaticResource AccentColorBrush}" />
                                    <Setter Property="Cursor" Value="Hand"></Setter>
                                </Trigger>
                                <Trigger Property="IsSelected" Value="True">
                                    <Setter Property="Background" Value="Transparent"></Setter>
                                </Trigger>
                                <Trigger Property="IsFocused" Value="True">
                                    <Setter Property="Background" Value="Transparent"></Setter>
                                </Trigger>
                            </Style.Triggers>
                        </Style>
                    </DataGrid.RowStyle>

                    <DataGrid.Columns>
                        <DataGridTextColumn Header="ID" Binding="{Binding ID}" Width="40" />
                        <DataGridTextColumn Header="TIME" Binding="{Binding LastUpdated, Converter={StaticResource DateTimeUTCToShortDateTimeConverter}}" Width="Auto" />
                        <DataGridTextColumn Header="ACTION" Binding="{Binding ActionType, Converter={StaticResource EnumToDescriptionConverter}}" Width="Auto"/>
                        <DataGridTextColumn Header="USER" Binding="{Binding User.Contact.FullName}" Width="Auto"/>
                        <DataGridTextColumn Header="RELATED OBJECT NAME" Binding="{Binding RelatedObjectName}" Width="Auto" />
                        <DataGridTextColumn Header="RELATED OBJECT ID" Binding="{Binding RelatedObjectGuid}" Width="Auto"  >
                            <DataGridTextColumn.CellStyle>
                                <Style TargetType="DataGridCell" BasedOn="{StaticResource {x:Type DataGridCell}}" >
                                    <Setter Property="BorderThickness" Value="0"/>
                                    <Setter Property="FocusVisualStyle" Value="{x:Null}"/>
                                    <Setter Property="VerticalContentAlignment" Value="Center"></Setter>
                                    <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType=UserControl},  Path=DataContext}"/>
                                    <Setter Property="ContextMenu">
                                        <Setter.Value>
                                            <ContextMenu DataContext="{Binding PlacementTarget.Tag, RelativeSource={RelativeSource Self}}" Padding="0" Margin="0" >
                                                <MenuItem Header="Copy (Ctrl+C)" Command="{Binding CopyRelateObjectIDCommand}" FontSize="12" Background="{StaticResource MainWindow.Background}">
                                                    <MenuItem.Icon>
                                                        <materialDesign:PackIcon Width="16"  Height="16"  Kind="ContentCopy" VerticalAlignment="Center"  Foreground="{StaticResource MainWindow.Foreground}"/>
                                                    </MenuItem.Icon>
                                                    <MenuItem.ItemContainerStyle>
                                                        <Style TargetType="MenuItem" BasedOn="{StaticResource MaterialDesignMenuItem}">
                                                            <Setter Property="Background" Value="Transparent"></Setter>
                                                            <Style.Triggers>
                                                                <Trigger Property="IsMouseOver" Value="True">
                                                                    <Setter Property="Background" Value="Transparent"></Setter>
                                                                </Trigger>
                                                            </Style.Triggers>
                                                        </Style>
                                                    </MenuItem.ItemContainerStyle>
                                                </MenuItem>
                                                <ContextMenu.Style>
                                                    <Style TargetType="{x:Type ContextMenu}"  BasedOn="{StaticResource MaterialDesignMenu}">
                                                        <Setter Property="Template">
                                                            <Setter.Value>
                                                                <ControlTemplate >
                                                                    <AdornerDecorator CacheMode="{Binding RelativeSource={RelativeSource Self}, Path=(wpf:ShadowAssist.CacheMode)}">
                                                                        <Border Background="{StaticResource MainWindow.Background}" Effect="{DynamicResource MaterialDesignShadowDepth1}" Margin="3" CornerRadius="2">
                                                                            <Grid RenderOptions.ClearTypeHint="Enabled" Margin="0">
                                                                                <ItemsPresenter x:Name="ItemsPresenter"  KeyboardNavigation.DirectionalNavigation="Cycle" Grid.IsSharedSizeScope="True"  SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" KeyboardNavigation.TabNavigation="Cycle"/>
                                                                            </Grid>
                                                                        </Border>
                                                                    </AdornerDecorator>
                                                                </ControlTemplate>
                                                            </Setter.Value>
                                                        </Setter>
                                                    </Style>
                                                </ContextMenu.Style>
                                            </ContextMenu>
                                        </Setter.Value>
                                    </Setter>
                                    <Style.Triggers>
                                        <Trigger Property="IsSelected" Value="True">
                                            <Setter Property="Background" Value="Transparent"></Setter>
                                            <Setter Property="Foreground" Value="{StaticResource AccentColorBrush}" />
                                        </Trigger>
                                    </Style.Triggers>
                                </Style>
                            </DataGridTextColumn.CellStyle>
                        </DataGridTextColumn>
                        <DataGridTextColumn Header="MESSAGE" Binding="{Binding Message}" Width="1*" />
                    </DataGrid.Columns>
                </DataGrid>
            </Grid>
            <Grid Grid.Row="1" Grid.Column="0"  Visibility="{Binding IsLoading,Converter={StaticResource BooleanToVisibilityConverter}}">
                <StackPanel Orientation="Vertical" HorizontalAlignment="Center" VerticalAlignment="Center">
                    <mahapps:ProgressRing Margin="20 60 20 40" Width="80" Height="80" IsActive="{Binding IsLoading}"></mahapps:ProgressRing>
                    <TextBlock Text="Loading..." HorizontalAlignment="Center" FontSize="20" FontStyle="Italic" VerticalAlignment="Center" Margin="0 20 0 0"></TextBlock>
                </StackPanel>
            </Grid>

            <Grid Grid.Row="0" Grid.Column="1" Margin="40 0 10 0">
                <Border  Padding="14 14 12 14" BorderBrush="DimGray" BorderThickness="0" Background="{StaticResource Logging.Background}" HorizontalAlignment="Stretch" VerticalAlignment="Stretch"  CornerRadius="2">
                    <Border.Effect>
                        <DropShadowEffect ShadowDepth="4" BlurRadius="10" Opacity="0.5"/>
                    </Border.Effect>
                    <DockPanel>
                        <TextBlock DockPanel.Dock="Left" Margin="10 0 0 0"  Foreground="{StaticResource DimGrayBrush}" FontSize="16" VerticalAlignment="Center" Width="150">Object Changes</TextBlock>
                        <Button  Width="Auto" HorizontalContentAlignment="Stretch" VerticalContentAlignment="Stretch" HorizontalAlignment="Right" DockPanel.Dock="Right" Command="{Binding CopyToClipBoardCommand}" >
                            <StackPanel Orientation="Horizontal" >
                                <materialDesign:PackIcon Width="16"  Height="16"  Kind="ContentCopy" VerticalAlignment="Center" Margin="-5 0 10 0"/>
                                <TextBlock  Text="Copy to Clipboard"  VerticalAlignment="Center"></TextBlock>
                            </StackPanel>
                        </Button>
                    </DockPanel>
                </Border>
            </Grid>
            <Border  Grid.Row="1" Grid.Column="1" Margin="40 0 10 10" IsEnabled="{Binding IsFree}" BorderThickness="1 0 1 1 " BorderBrush="{StaticResource LightGrayBrush100}" Background="{StaticResource TransparentBackgroundBrush}">
                <DockPanel >
                    <TextBlock DockPanel.Dock="Top" Height="40" Text="{Binding DifferenceObject.Name, Mode=OneWay}" VerticalAlignment="Center"  Padding="5" FontSize="18" HorizontalAlignment="Center" ></TextBlock>
                    <TreeView x:Name="treeView" ItemsSource="{Binding DifferenceObject.Children, Mode=OneWay}" >
                        <TreeView.ItemContainerStyle>
                            <Style TargetType="TreeViewItem" BasedOn="{StaticResource {x:Type TreeViewItem}}">
                                <Setter Property="Template">
                                    <Setter.Value>
                                        <ControlTemplate TargetType="{x:Type TreeViewItem}">
                                            <Grid>
                                                <Grid.ColumnDefinitions>
                                                    <ColumnDefinition MinWidth="19" Width="Auto"/>
                                                    <ColumnDefinition Width="Auto"/>
                                                    <ColumnDefinition Width="*"/>
                                                </Grid.ColumnDefinitions>
                                                <Grid.RowDefinitions>
                                                    <RowDefinition Height="Auto"/>
                                                    <RowDefinition/>
                                                </Grid.RowDefinitions>
                                                <ToggleButton x:Name="Expander" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" 
                                      Style="{StaticResource MaterialDesignExpandCollapseToggleStyle}"
                                      Foreground="{TemplateBinding Foreground}"
                                      Margin="8 0 8 0"
                                      VerticalAlignment="Center"
                                              />
                                                <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.Column="1" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                                                    <ContentPresenter x:Name="PART_Header" ContentSource="Header" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                                                </Border>
                                                <ItemsPresenter x:Name="ItemsHost" Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="1"/>
                                            </Grid>
                                            <ControlTemplate.Triggers>
                                                <Trigger Property="IsExpanded" Value="false">
                                                    <Setter Property="Visibility" TargetName="ItemsHost" Value="Collapsed"/>
                                                </Trigger>
                                                <Trigger Property="HasItems" Value="false">
                                                    <Setter Property="Visibility" TargetName="Expander" Value="Hidden"/>
                                                </Trigger>
                                                <MultiTrigger>
                                                    <MultiTrigger.Conditions>
                                                        <Condition Property="IsSelected" Value="true"/>
                                                        <Condition Property="IsSelectionActive" Value="false"/>
                                                    </MultiTrigger.Conditions>
                                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.InactiveSelectionHighlightTextBrushKey}}"/>
                                                </MultiTrigger>
                                                <Trigger Property="IsEnabled" Value="false">
                                                    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                                                </Trigger>
                                            </ControlTemplate.Triggers>
                                        </ControlTemplate>
                                    </Setter.Value>
                                </Setter>
                                <Setter Property="IsExpanded" Value="True" />
                                <Style.Triggers>
                                    <Trigger Property="IsMouseOver" Value="True">
                                        <Setter Property="Background" Value="Transparent"></Setter>
                                    </Trigger>
                                    <Trigger Property="IsFocused" Value="True">
                                        <Setter Property="Background" Value="Transparent"></Setter>
                                    </Trigger>
                                    <Trigger Property="IsSelected" Value="True">
                                        <Setter Property="Background" Value="Transparent"></Setter>
                                    </Trigger>
                                </Style.Triggers>
                            </Style>
                        </TreeView.ItemContainerStyle>
                        <TreeView.Resources>
                            <HierarchicalDataTemplate DataType="{x:Type diff:ActionLogDifference}" ItemsSource="{Binding Children}">
                                <TextBlock Text="{Binding Name}" Margin="5 0 0 0"  Foreground ="{StaticResource MainWindow.Foreground}"/>
                            </HierarchicalDataTemplate>

                            <DataTemplate DataType="{x:Type diff:ActionLogDifferenceValue}">
                                <TextBlock Margin="5 0 0 0"  Foreground ="{StaticResource MainWindow.Foreground}">
                                        <Run Text="{Binding Name}"/>
                                        <Run>: </Run>
                                        <Run Text="{Binding Before,Mode=OneWay}" Foreground="{StaticResource DimGrayBrush}"/>
                                        <Run> | </Run>
                                        <Run Text="{Binding After,Mode=OneWay}" Foreground="{StaticResource RedBrush100}"/>
                                </TextBlock>
                            </DataTemplate>
                        </TreeView.Resources>
                    </TreeView>

                </DockPanel>
            </Border>
            <mahapps:ProgressRing Grid.Row="1" Grid.Column="1" Margin="20 0 20 40" Width="80" Height="80" IsActive="{Binding IsLoadingDifferences}"></mahapps:ProgressRing>

        </Grid>
    </Grid>
</UserControl>
> leafCount, int totalLength) { Debug.Assert(leafCount > 0); Debug.Assert(totalLength > 0); RopeNode<T> result = new RopeNode<T>(); result.length = totalLength; if (leafCount == 1) { result.contents = new T[NodeSize]; } else { int rightSide = leafCount / 2; int leftSide = leafCount - rightSide; int leftLength = leftSide * NodeSize; result.left = CreateNodes(leftSide, leftLength); result.right = CreateNodes(rightSide, totalLength - leftLength); result.height = (byte)(1 + Math.Max(result.left.height, result.right.height)); } return result; } /// <summary> /// Balances this node and recomputes the 'height' field. /// This method assumes that the children of this node are already balanced and have an up-to-date 'height' value. /// </summary> internal void Rebalance() { // Rebalance() shouldn't be called on shared nodes - it's only called after modifications! Debug.Assert(!isShared); // leaf nodes are always balanced (we don't use 'height' to detect leaf nodes here // because Balance is supposed to recompute the height). if (left == null) return; // ensure we didn't miss a MergeIfPossible step Debug.Assert(this.length > NodeSize); // We need to loop until it's balanced. Rotations might cause two small leaves to combine to a larger one, // which changes the height and might mean we need additional balancing steps. while (Math.Abs(this.Balance) > 1) { // AVL balancing // note: because we don't care about the identity of concat nodes, this works a little different than usual // tree rotations: in our implementation, the "this" node will stay at the top, only its children are rearranged if (this.Balance > 1) { if (right.Balance < 0) { right = right.CloneIfShared(); right.RotateRight(); } this.RotateLeft(); // If 'this' was unbalanced by more than 2, we've shifted some of the inbalance to the left node; so rebalance that. this.left.Rebalance(); } else if (this.Balance < -1) { if (left.Balance > 0) { left = left.CloneIfShared(); left.RotateLeft(); } this.RotateRight(); // If 'this' was unbalanced by more than 2, we've shifted some of the inbalance to the right node; so rebalance that. this.right.Rebalance(); } } Debug.Assert(Math.Abs(this.Balance) <= 1); this.height = (byte)(1 + Math.Max(left.height, right.height)); } void RotateLeft() { Debug.Assert(!isShared); /* Rotate tree to the left * * this this * / \ / \ * A right ===> left C * / \ / \ * B C A B */ RopeNode<T> a = left; RopeNode<T> b = right.left; RopeNode<T> c = right.right; // reuse right concat node, if possible this.left = right.isShared ? new RopeNode<T>() : right; this.left.left = a; this.left.right = b; this.left.length = a.length + b.length; this.left.height = (byte)(1 + Math.Max(a.height, b.height)); this.right = c; this.left.MergeIfPossible(); } void RotateRight() { Debug.Assert(!isShared); /* Rotate tree to the right * * this this * / \ / \ * left C ===> A right * / \ / \ * A B B C */ RopeNode<T> a = left.left; RopeNode<T> b = left.right; RopeNode<T> c = right; // reuse left concat node, if possible this.right = left.isShared ? new RopeNode<T>() : left; this.right.left = b; this.right.right = c; this.right.length = b.length + c.length; this.right.height = (byte)(1 + Math.Max(b.height, c.height)); this.left = a; this.right.MergeIfPossible(); } void MergeIfPossible() { Debug.Assert(!isShared); if (this.length <= NodeSize) { // Convert this concat node to leaf node. // We know left and right cannot be concat nodes (they would have merged already), // but they could be function nodes. this.height = 0; int lengthOnLeftSide = this.left.length; if (this.left.isShared) { this.contents = new T[NodeSize]; left.CopyTo(0, this.contents, 0, lengthOnLeftSide); } else { // must be a leaf node: function nodes are always marked shared Debug.Assert(this.left.contents != null); // steal buffer from left side this.contents = this.left.contents; #if DEBUG // In debug builds, explicitly mark left node as 'damaged' - but no one else should be using it // because it's not shared. this.left.contents = Empty<T>.Array; #endif } this.left = null; right.CopyTo(0, this.contents, lengthOnLeftSide, this.right.length); this.right = null; } } /// <summary> /// Copies from the array to this node. /// </summary> internal RopeNode<T> StoreElements(int index, T[] array, int arrayIndex, int count) { RopeNode<T> result = this.CloneIfShared(); // result cannot be function node after a call to Clone() if (result.height == 0) { // leaf node: Array.Copy(array, arrayIndex, result.contents, index, count); } else { // concat node: if (index + count <= result.left.length) { result.left = result.left.StoreElements(index, array, arrayIndex, count); } else if (index >= this.left.length) { result.right = result.right.StoreElements(index - result.left.length, array, arrayIndex, count); } else { int amountInLeft = result.left.length - index; result.left = result.left.StoreElements(index, array, arrayIndex, amountInLeft); result.right = result.right.StoreElements(0, array, arrayIndex + amountInLeft, count - amountInLeft); } result.Rebalance(); // tree layout might have changed if function nodes were replaced with their content } return result; } /// <summary> /// Copies from this node to the array. /// </summary> internal void CopyTo(int index, T[] array, int arrayIndex, int count) { if (height == 0) { if (this.contents == null) { // function node this.GetContentNode().CopyTo(index, array, arrayIndex, count); } else { // leaf node Array.Copy(this.contents, index, array, arrayIndex, count); } } else { // concat node if (index + count <= this.left.length) { this.left.CopyTo(index, array, arrayIndex, count); } else if (index >= this.left.length) { this.right.CopyTo(index - this.left.length, array, arrayIndex, count); } else { int amountInLeft = this.left.length - index; this.left.CopyTo(index, array, arrayIndex, amountInLeft); this.right.CopyTo(0, array, arrayIndex + amountInLeft, count - amountInLeft); } } } internal RopeNode<T> SetElement(int offset, T value) { RopeNode<T> result = CloneIfShared(); // result of CloneIfShared() is leaf or concat node if (result.height == 0) { result.contents[offset] = value; } else { if (offset < result.left.length) { result.left = result.left.SetElement(offset, value); } else { result.right = result.right.SetElement(offset - result.left.length, value); } result.Rebalance(); // tree layout might have changed if function nodes were replaced with their content } return result; } internal static RopeNode<T> Concat(RopeNode<T> left, RopeNode<T> right) { if (left.length == 0) return right; if (right.length == 0) return left; if (left.length + right.length <= NodeSize) { left = left.CloneIfShared(); // left is guaranteed to be leaf node after cloning: // - it cannot be function node (due to clone) // - it cannot be concat node (too short) right.CopyTo(0, left.contents, left.length, right.length); left.length += right.length; return left; } else { RopeNode<T> concatNode = new RopeNode<T>(); concatNode.left = left; concatNode.right = right; concatNode.length = left.length + right.length; concatNode.Rebalance(); return concatNode; } } /// <summary> /// Splits this leaf node at offset and returns a new node with the part of the text after offset. /// </summary> RopeNode<T> SplitAfter(int offset) { Debug.Assert(!isShared && height == 0 && contents != null); RopeNode<T> newPart = new RopeNode<T>(); newPart.contents = new T[NodeSize]; newPart.length = this.length - offset; Array.Copy(this.contents, offset, newPart.contents, 0, newPart.length); this.length = offset; return newPart; } internal RopeNode<T> Insert(int offset, RopeNode<T> newElements) { if (offset == 0) { return Concat(newElements, this); } else if (offset == this.length) { return Concat(this, newElements); } // first clone this node (converts function nodes to leaf or concat nodes) RopeNode<T> result = CloneIfShared(); if (result.height == 0) { // leaf node: we'll need to split this node RopeNode<T> left = result; RopeNode<T> right = left.SplitAfter(offset); return Concat(Concat(left, newElements), right); } else { // concat node if (offset < result.left.length) { result.left = result.left.Insert(offset, newElements); } else { result.right = result.right.Insert(offset - result.left.length, newElements); } result.length += newElements.length; result.Rebalance(); return result; } } internal RopeNode<T> Insert(int offset, T[] array, int arrayIndex, int count) { Debug.Assert(count > 0); if (this.length + count < RopeNode<char>.NodeSize) { RopeNode<T> result = CloneIfShared(); // result must be leaf node (Clone never returns function nodes, too short for concat node) int lengthAfterOffset = result.length - offset; T[] resultContents = result.contents; for (int i = lengthAfterOffset; i >= 0; i--) { resultContents[i + offset + count] = resultContents[i + offset]; } Array.Copy(array, arrayIndex, resultContents, offset, count); result.length += count; return result; } else if (height == 0) { // TODO: implement this more efficiently? return Insert(offset, CreateFromArray(array, arrayIndex, count)); } else { // this is a concat node (both leafs and function nodes are handled by the case above) RopeNode<T> result = CloneIfShared(); if (offset < result.left.length) { result.left = result.left.Insert(offset, array, arrayIndex, count); } else { result.right = result.right.Insert(offset - result.left.length, array, arrayIndex, count); } result.length += count; result.Rebalance(); return result; } } internal RopeNode<T> RemoveRange(int index, int count) { Debug.Assert(count > 0); // produce empty node when one node is deleted completely if (index == 0 && count == this.length) return emptyRopeNode; int endIndex = index + count; RopeNode<T> result = CloneIfShared(); // convert function node to concat/leaf if (result.height == 0) { int remainingAfterEnd = result.length - endIndex; for (int i = 0; i < remainingAfterEnd; i++) { result.contents[index + i] = result.contents[endIndex + i]; } result.length -= count; } else { if (endIndex <= result.left.length) { // deletion is only within the left part result.left = result.left.RemoveRange(index, count); } else if (index >= result.left.length) { // deletion is only within the right part result.right = result.right.RemoveRange(index - result.left.length, count); } else { // deletion overlaps both parts int deletionAmountOnLeftSide = result.left.length - index; result.left = result.left.RemoveRange(index, deletionAmountOnLeftSide); result.right = result.right.RemoveRange(0, count - deletionAmountOnLeftSide); } // The deletion might have introduced empty nodes. Those must be removed. if (result.left.length == 0) return result.right; if (result.right.length == 0) return result.left; result.length -= count; result.MergeIfPossible(); result.Rebalance(); } return result; } #region Debug Output #if DEBUG internal virtual void AppendTreeToString(StringBuilder b, int indent) { b.AppendLine(ToString()); indent += 2; if (left != null) { b.Append(' ', indent); b.Append("L: "); left.AppendTreeToString(b, indent); } if (right != null) { b.Append(' ', indent); b.Append("R: "); right.AppendTreeToString(b, indent); } } public override string ToString() { if (contents != null) { char[] charContents = contents as char[]; if (charContents != null) return "[Leaf length=" + length + ", isShared=" + isShared + ", text=\"" + new string(charContents, 0, length) + "\"]"; else return "[Leaf length=" + length + ", isShared=" + isShared + "\"]"; } else { return "[Concat length=" + length + ", isShared=" + isShared + ", height=" + height + ", Balance=" + this.Balance + "]"; } } internal string GetTreeAsString() { StringBuilder b = new StringBuilder(); AppendTreeToString(b, 0); return b.ToString(); } #endif #endregion /// <summary> /// Gets the root node of the subtree from a lazily evaluated function node. /// Such nodes are always marked as shared. /// GetContentNode() will return either a Concat or Leaf node, never another FunctionNode. /// </summary> internal virtual RopeNode<T> GetContentNode() { throw new InvalidOperationException("Called GetContentNode() on non-FunctionNode."); } } sealed class FunctionNode<T> : RopeNode<T> { Func<Rope<T>> initializer; RopeNode<T> cachedResults; public FunctionNode(int length, Func<Rope<T>> initializer) { Debug.Assert(length > 0); Debug.Assert(initializer != null); this.length = length; this.initializer = initializer; // Function nodes are immediately shared, but cannot be cloned. // This ensures we evaluate every initializer only once. this.isShared = true; } internal override RopeNode<T> GetContentNode() { lock (this) { if (this.cachedResults == null) { if (this.initializer == null) throw new InvalidOperationException("Trying to load this node recursively; or: a previous call to a rope initializer failed."); Func<Rope<T>> initializerCopy = this.initializer; this.initializer = null; Rope<T> resultRope = initializerCopy(); if (resultRope == null) throw new InvalidOperationException("Rope initializer returned null."); RopeNode<T> resultNode = resultRope.root; resultNode.Publish(); // result is shared between returned rope and the rope containing this function node if (resultNode.length != this.length) throw new InvalidOperationException("Rope initializer returned rope with incorrect length."); if (resultNode.height == 0 && resultNode.contents == null) { // ResultNode is another function node. // We want to guarantee that GetContentNode() never returns function nodes, so we have to // go down further in the tree. this.cachedResults = resultNode.GetContentNode(); } else { this.cachedResults = resultNode; } } return this.cachedResults; } } #if DEBUG internal override void AppendTreeToString(StringBuilder b, int indent) { RopeNode<T> resultNode; lock (this) { b.AppendLine(ToString()); resultNode = cachedResults; } indent += 2; if (resultNode != null) { b.Append(' ', indent); b.Append("C: "); resultNode.AppendTreeToString(b, indent); } } public override string ToString() { return "[FunctionNode length=" + length + " initializerRan=" + (initializer == null) + "]"; } #endif } }