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
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
using System.ComponentModel;
using System.Windows;
using System.Windows.Controls;
using ScreenGrab.Extensions;

namespace ScreenGrab;

/// <summary>
///     Source <see href="https://github.com/budul100/WpfAutoGrid.Core" />
///     Defines a flexible grid area that consists of columns and rows.
///     Depending on the orientation, either the rows or the columns are auto-generated,
///     and the children's position is set according to their index.
///     Partially based on work at http://rachel53461.wordpress.com/2011/09/17/wpf-grids-rowcolumn-count-properties/
/// </summary>
public class AutoGrid : Grid
{
    #region Protected Methods

    /// <summary>
    ///     Measures the children of a <see cref="T:System.Windows.Controls.Grid" /> in anticipation of arranging them during
    ///     the <see cref="M:ArrangeOverride" /> pass.
    /// </summary>
    /// <param name="constraint">Indicates an upper limit size that should not be exceeded.</param>
    /// <returns>
    ///     <see cref="Size" /> that represents the required size to arrange child content.
    /// </returns>
    protected override Size MeasureOverride(Size constraint)
    {
        PerformLayout();
        return base.MeasureOverride(constraint);
    }

    #endregion Protected Methods

    #region Public Fields

    public static readonly DependencyProperty ChildHorizontalAlignmentProperty = DependencyProperty.Register(
        "ChildHorizontalAlignment",
        typeof(HorizontalAlignment?),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure,
            OnChildHorizontalAlignmentChanged));

    public static readonly DependencyProperty ChildMarginProperty = DependencyProperty.Register(
        "ChildMargin",
        typeof(Thickness?),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure, OnChildMarginChanged));

    public static readonly DependencyProperty ChildVerticalAlignmentProperty = DependencyProperty.Register(
        "ChildVerticalAlignment",
        typeof(VerticalAlignment?),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata(null, FrameworkPropertyMetadataOptions.AffectsMeasure,
            OnChildVerticalAlignmentChanged));

    public static readonly DependencyProperty ColumnCountProperty = DependencyProperty.RegisterAttached(
        "ColumnCount",
        typeof(int),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsMeasure, ColumnCountChanged));

    public static readonly DependencyProperty ColumnsProperty = DependencyProperty.RegisterAttached(
        "Columns",
        typeof(string),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsMeasure, ColumnsChanged));

    public static readonly DependencyProperty ColumnWidthProperty = DependencyProperty.RegisterAttached(
        "ColumnWidth",
        typeof(GridLength),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata(GridLength.Auto, FrameworkPropertyMetadataOptions.AffectsMeasure,
            FixedColumnWidthChanged));

    public static readonly DependencyProperty IsAutoIndexingProperty = DependencyProperty.Register(
        "IsAutoIndexing",
        typeof(bool),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata(true, FrameworkPropertyMetadataOptions.AffectsMeasure));

    public static readonly DependencyProperty OrientationProperty = DependencyProperty.Register(
        "Orientation",
        typeof(Orientation),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata(Orientation.Horizontal, FrameworkPropertyMetadataOptions.AffectsMeasure));

    public static readonly DependencyProperty RowCountProperty = DependencyProperty.RegisterAttached(
        "RowCount",
        typeof(int),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata(1, FrameworkPropertyMetadataOptions.AffectsMeasure, RowCountChanged));

    public static readonly DependencyProperty RowHeightProperty = DependencyProperty.RegisterAttached(
        "RowHeight",
        typeof(GridLength),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata(GridLength.Auto, FrameworkPropertyMetadataOptions.AffectsMeasure,
            FixedRowHeightChanged));

    public static readonly DependencyProperty RowsProperty = DependencyProperty.RegisterAttached(
        "Rows",
        typeof(string),
        typeof(AutoGrid),
        new FrameworkPropertyMetadata("", FrameworkPropertyMetadataOptions.AffectsMeasure, RowsChanged));

    #endregion Public Fields

    #region Public Properties

    /// <summary>
    ///     Gets or sets the child horizontal alignment.
    /// </summary>
    /// <value>The child horizontal alignment.</value>
    [Category("Layout")]
    [Description("Presets the horizontal alignment of all child controls")]
    public HorizontalAlignment? ChildHorizontalAlignment
    {
        get => (HorizontalAlignment?)GetValue(ChildHorizontalAlignmentProperty);
        set => SetValue(ChildHorizontalAlignmentProperty, value);
    }

    /// <summary>
    ///     Gets or sets the child margin.
    /// </summary>
    /// <value>The child margin.</value>
    [Category("Layout")]
    [Description("Presets the margin of all child controls")]
    public Thickness? ChildMargin
    {
        get => (Thickness?)GetValue(ChildMarginProperty);
        set => SetValue(ChildMarginProperty, value);
    }

    /// <summary>
    ///     Gets or sets the child vertical alignment.
    /// </summary>
    /// <value>The child vertical alignment.</value>
    [Category("Layout")]
    [Description("Presets the vertical alignment of all child controls")]
    public VerticalAlignment? ChildVerticalAlignment
    {
        get => (VerticalAlignment?)GetValue(ChildVerticalAlignmentProperty);
        set => SetValue(ChildVerticalAlignmentProperty, value);
    }

    /// <summary>
    ///     Gets or sets the column count
    /// </summary>
    [Category("Layout")]
    [Description("Defines a set number of columns")]
    public int ColumnCount
    {
        get => (int)GetValue(ColumnCountProperty);
        set => SetValue(ColumnCountProperty, value);
    }

    /// <summary>
    ///     Gets or sets the columns
    /// </summary>
    [Category("Layout")]
    [Description("Defines all columns using comma separated grid length notation")]
    public string Columns
    {
        get => (string)GetValue(ColumnsProperty);
        set => SetValue(ColumnsProperty, value);
    }

    /// <summary>
    ///     Gets or sets the fixed column width
    /// </summary>
    [Category("Layout")]
    [Description("Presets the width of all columns set using the ColumnCount property")]
    public GridLength ColumnWidth
    {
        get => (GridLength)GetValue(ColumnWidthProperty);
        set => SetValue(ColumnWidthProperty, value);
    }

    /// <summary>
    ///     Gets or sets a value indicating whether the children are automatically indexed.
    ///     <remarks>
    ///         The default is <c>true</c>.
    ///         Note that if children are already indexed, setting this property to <c>false</c> will not remove their indices.
    ///     </remarks>
    /// </summary>
    [Category("Layout")]
    [Description("Set to false to disable the auto layout functionality")]
    public bool IsAutoIndexing
    {
        get => (bool)GetValue(IsAutoIndexingProperty);
        set => SetValue(IsAutoIndexingProperty, value);
    }

    /// <summary>
    ///     Gets or sets the orientation.
    ///     <remarks>The default is Vertical.</remarks>
    /// </summary>
    /// <value>The orientation.</value>
    [Category("Layout")]
    [Description(
        "Defines the directionality of the autolayout. Use vertical for a column first layout, horizontal for a row first layout.")]
    public Orientation Orientation
    {
        get => (Orientation)GetValue(OrientationProperty);
        set => SetValue(OrientationProperty, value);
    }

    /// <summary>
    ///     Gets or sets the number of rows
    /// </summary>
    [Category("Layout")]
    [Description("Defines a set number of rows")]
    public int RowCount
    {
        get => (int)GetValue(RowCountProperty);
        set => SetValue(RowCountProperty, value);
    }

    /// <summary>
    ///     Gets or sets the fixed row height
    /// </summary>
    [Category("Layout")]
    [Description("Presets the height of all rows set using the RowCount property")]
    public GridLength RowHeight
    {
        get => (GridLength)GetValue(RowHeightProperty);
        set => SetValue(RowHeightProperty, value);
    }

    /// <summary>
    ///     Gets or sets the rows
    /// </summary>
    [Category("Layout")]
    [Description("Defines all rows using comma separated grid length notation")]
    public string Rows
    {
        get => (string)GetValue(RowsProperty);
        set => SetValue(RowsProperty, value);
    }

    #endregion Public Properties

    #region Public Methods

    /// <summary>
    ///     Handles the column count changed event
    /// </summary>
    public static void ColumnCountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if ((int)e.NewValue < 0)
            return;

        if (d is not AutoGrid grid) return;
        //var grid = d as AutoGrid;

        // look for an existing column definition for the height
        var width = GridLength.Auto;
        if (grid.ColumnDefinitions.Count > 0)
            width = grid.ColumnDefinitions[0].Width;

        // clear and rebuild
        grid.ColumnDefinitions.Clear();
        for (var i = 0; i < (int)e.NewValue; i++)
            grid.ColumnDefinitions.Add(
                new ColumnDefinition { Width = width });
    }

    /// <summary>
    ///     Handle the columns changed event
    /// </summary>
    public static void ColumnsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (string.IsNullOrEmpty((string)e.NewValue))
            return;

        if (d is not AutoGrid grid) return;
        //var grid = d as AutoGrid;
        grid.ColumnDefinitions.Clear();

        var defs = Parse((string)e.NewValue);
        foreach (var def in defs)
            grid.ColumnDefinitions.Add(new ColumnDefinition { Width = def });
    }

    /// <summary>
    ///     Handle the fixed column width changed event
    /// </summary>
    public static void FixedColumnWidthChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not AutoGrid grid) return;
        //var grid = d as AutoGrid;

        // add a default column if missing
        if (grid.ColumnDefinitions.Count == 0)
            grid.ColumnDefinitions.Add(new ColumnDefinition());

        // set all existing columns to this width
        for (var i = 0; i < grid.ColumnDefinitions.Count; i++)
            grid.ColumnDefinitions[i].Width = (GridLength)e.NewValue;
    }

    /// <summary>
    ///     Handle the fixed row height changed event
    /// </summary>
    public static void FixedRowHeightChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not AutoGrid grid) return;
        //var grid = d as AutoGrid;

        // add a default row if missing
        if (grid.RowDefinitions.Count == 0)
            grid.RowDefinitions.Add(new RowDefinition());

        // set all existing rows to this height
        for (var i = 0; i < grid.RowDefinitions.Count; i++)
            grid.RowDefinitions[i].Height = (GridLength)e.NewValue;
    }

    /// <summary>
    ///     Parse an array of grid lengths from comma delim text
    /// </summary>
    public static GridLength[] Parse(string text)
    {
        var tokens = text.Split(',');
        var definitions = new GridLength[tokens.Length];
        for (var i = 0; i < tokens.Length; i++)
        {
            var str = tokens[i];
            double value;

            // ratio
            if (str.Contains('*'))
            {
                if (!double.TryParse(str.Replace("*", ""), out value))
                    value = 1.0;

                definitions[i] = new GridLength(value, GridUnitType.Star);
                continue;
            }

            // pixels
            if (double.TryParse(str, out value))
            {
                definitions[i] = new GridLength(value);
                continue;
            }

            // auto
            definitions[i] = GridLength.Auto;
        }

        return definitions;
    }

    /// <summary>
    ///     Handles the row count changed event
    /// </summary>
    public static void RowCountChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if ((int)e.NewValue < 0)
            return;

        if (d is not AutoGrid grid) return;
        //var grid = d as AutoGrid;

        // look for an existing row to get the height
        var height = GridLength.Auto;
        if (grid.RowDefinitions.Count > 0)
            height = grid.RowDefinitions[0].Height;

        // clear and rebuild
        grid.RowDefinitions.Clear();
        for (var i = 0; i < (int)e.NewValue; i++)
            grid.RowDefinitions.Add(
                new RowDefinition { Height = height });
    }

    /// <summary>
    ///     Handle the rows changed event
    /// </summary>
    public static void RowsChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (string.IsNullOrEmpty((string)e.NewValue))
            return;

        if (d is not AutoGrid grid) return;
        //var grid = d as AutoGrid;
        grid.RowDefinitions.Clear();

        var defs = Parse((string)e.NewValue);
        foreach (var def in defs)
            grid.RowDefinitions.Add(new RowDefinition { Height = def });
    }

    #endregion Public Methods

    #region Private Methods

    /// <summary>
    ///     Called when [child horizontal alignment changed].
    /// </summary>
    private static void OnChildHorizontalAlignmentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not AutoGrid grid) return;
        //var grid = d as AutoGrid;
        foreach (UIElement child in grid.Children)
            if (grid.ChildHorizontalAlignment.HasValue)
                child.SetValue(HorizontalAlignmentProperty, grid.ChildHorizontalAlignment);
            else
                child.SetValue(HorizontalAlignmentProperty, DependencyProperty.UnsetValue);
    }

    /// <summary>
    ///     Called when [child layout changed].
    /// </summary>
    private static void OnChildMarginChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not AutoGrid grid) return;
        //var grid = d as AutoGrid;
        foreach (UIElement child in grid.Children)
            if (grid.ChildMargin.HasValue)
                child.SetValue(MarginProperty, grid.ChildMargin);
            else
                child.SetValue(MarginProperty, DependencyProperty.UnsetValue);
    }

    /// <summary>
    ///     Called when [child vertical alignment changed].
    /// </summary>
    private static void OnChildVerticalAlignmentChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        if (d is not AutoGrid grid) return;
        //var grid = d as AutoGrid;
        foreach (UIElement child in grid.Children)
            if (grid.ChildVerticalAlignment.HasValue)
                child.SetValue(VerticalAlignmentProperty, grid.ChildVerticalAlignment);
            else
                child.SetValue(VerticalAlignmentProperty, DependencyProperty.UnsetValue);
    }

    ///// <summary>
    ///// Handled the redraw properties changed event
    ///// </summary>
    //private static void OnPropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    //{ }

    /// <summary>
    ///     Apply child margins and layout effects such as alignment
    /// </summary>
    private void ApplyChildLayout(UIElement child)
    {
        if (ChildMargin != null) child.SetIfDefault(MarginProperty, ChildMargin.Value);
        if (ChildHorizontalAlignment != null)
            child.SetIfDefault(HorizontalAlignmentProperty, ChildHorizontalAlignment.Value);
        if (ChildVerticalAlignment != null) child.SetIfDefault(VerticalAlignmentProperty, ChildVerticalAlignment.Value);
    }

    /// <summary>
    ///     Clamp a value to its maximum.
    /// </summary>
    private int Clamp(int value, int max)
    {
        return value > max ? max : value;
    }

    /// <summary>
    ///     Perform the grid layout of row and column indexes
    /// </summary>
    private void PerformLayout()
    {
        var fillRowFirst = Orientation == Orientation.Horizontal;
        var rowCount = RowDefinitions.Count;
        var colCount = ColumnDefinitions.Count;

        if (rowCount == 0 || colCount == 0)
            return;

        var position = 0;
        var skip = new bool[rowCount, colCount];
        foreach (UIElement child in Children)
        {
            var childIsCollapsed = child.Visibility == Visibility.Collapsed;
            if (IsAutoIndexing && !childIsCollapsed)
            {
                if (fillRowFirst)
                {
                    var row = Clamp(position / colCount, rowCount - 1);
                    var col = Clamp(position % colCount, colCount - 1);
                    if (skip[row, col])
                    {
                        position++;
                        row = position / colCount;
                        col = position % colCount;
                    }

                    SetRow(child, row);
                    SetColumn(child, col);
                    position += GetColumnSpan(child);

                    var offset = GetRowSpan(child) - 1;
                    while (offset > 0) skip[row + offset--, col] = true;
                }
                else
                {
                    var row = Clamp(position % rowCount, rowCount - 1);
                    var col = Clamp(position / rowCount, colCount - 1);
                    if (skip[row, col])
                    {
                        position++;
                        row = position % rowCount;
                        col = position / rowCount;
                    }

                    SetRow(child, row);
                    SetColumn(child, col);
                    position += GetRowSpan(child);

                    var offset = GetColumnSpan(child) - 1;
                    while (offset > 0) skip[row, col + offset--] = true;
                }
            }

            ApplyChildLayout(child);
        }
    }

    #endregion Private Methods
}