aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Package/Options/QtVersionsTable.cs
blob: ddcb90d9402a1cfade4da697e21e543455ba6d23 (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
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
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
/****************************************************************************
**
** Copyright (C) 2022 The Qt Company Ltd.
** Contact: https://www.qt.io/licensing/
**
** This file is part of the Qt VS Tools.
**
** $QT_BEGIN_LICENSE:GPL-EXCEPT$
** Commercial License Usage
** Licensees holding valid commercial Qt licenses may use this file in
** accordance with the commercial license agreement provided with the
** Software or, alternatively, in accordance with the terms contained in
** a written agreement between you and The Qt Company. For licensing terms
** and conditions see https://www.qt.io/terms-conditions. For further
** information use the contact form at https://www.qt.io/contact-us.
**
** GNU General Public License Usage
** Alternatively, this file may be used under the terms of the GNU
** General Public License version 3 as published by the Free Software
** Foundation with exceptions as appearing in the file LICENSE.GPL3-EXCEPT
** included in the packaging of this file. Please review the following
** information to ensure the GNU General Public License requirements will
** be met: https://www.gnu.org/licenses/gpl-3.0.html.
**
** $QT_END_LICENSE$
**
****************************************************************************/

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Interop;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using Microsoft.Win32;

namespace QtVsTools.Options
{
    using Common;
    using static Common.EnumExt;

    public enum BuildHost
    {
        [String("Windows")] Windows,
        [String("Linux SSH")] LinuxSSH,
        [String("Linux WSL")] LinuxWSL,
    }

    public partial class QtVersionsTable : UserControl
    {
        LazyFactory Lazy { get; } = new LazyFactory();

        public QtVersionsTable()
        {
            InitializeComponent();
        }

        [Flags] public enum Column
        {
            IsDefault = 0x10,
            VersionName = 0x20,
            Host = 0x40,
            Path = 0x80,
            Compiler = 0x100
        }

        [Flags] public enum State
        {
            Unknown = 0x00,
            Existing = 0x01,
            Removed = 0x02,
            Modified = 0x04
        }

        public class Field
        {
            public string Value { get; set; }
            public Control Control { get; set; }
            public DataGridCell Cell { get; set; }
            public string ValidationError { get; set; }
            public bool IsValid => string.IsNullOrEmpty(ValidationError);
            public ToolTip ToolTip
                => IsValid ? null : new ToolTip() { Content = ValidationError };
            public int SelectionStart { get; set; }
        }

        public class Row
        {
            static LazyFactory StaticLazy { get; } = new LazyFactory();
            LazyFactory Lazy { get; } = new LazyFactory();

            public Dictionary<Column, Field> Fields => Lazy.Get(() =>
                Fields, () => GetValues<Column>()
                    .Select(field => new KeyValuePair<Column, Field>(field, null))
                    .ToDictionary(keyValue => keyValue.Key, keyValue => keyValue.Value));

            public Field FieldDefault => Fields[Column.IsDefault]
                ?? (Fields[Column.IsDefault] = new Field());
            public bool IsDefault
            {
                get => (FieldDefault.Value == true.ToString());
                set => FieldDefault.Value = value.ToString();
            }

            public Field FieldVersionName => Fields[Column.VersionName]
                ?? (Fields[Column.VersionName] = new Field());
            public string VersionName
            {
                get => FieldVersionName.Value;
                set => FieldVersionName.Value = value;
            }
            public string InitialVersionName { get; set; }

            public Field FieldHost => Fields[Column.Host]
                ?? (Fields[Column.Host] = new Field());
            public BuildHost Host
            {
                get => FieldHost.Value.Cast(defaultValue: BuildHost.Windows);
                set => FieldHost.Value = value.Cast<string>();
            }

            public Field FieldPath => Fields[Column.Path]
                ?? (Fields[Column.Path] = new Field());
            public string Path
            {
                get => FieldPath.Value;
                set => FieldPath.Value = value;
            }

            public Field FieldCompiler => Fields[Column.Compiler]
                ?? (Fields[Column.Compiler] = new Field());
            public string Compiler
            {
                get => FieldCompiler.Value;
                set => FieldCompiler.Value = value;
            }

            public bool LastRow { get; set; }

            public bool DefaultEnabled => !IsDefault && !LastRow;
            public bool NameEnabled => !LastRow;
            public bool CompilerEnabled => (Host != BuildHost.Windows);
            public Visibility RowContentVisibility
                => LastRow ? Visibility.Hidden : Visibility.Visible;
            public Visibility ButtonAddVisibility
                => LastRow ? Visibility.Visible : Visibility.Hidden;
            public Visibility ButtonBrowseVisibility
                => (!LastRow && Host == BuildHost.Windows) ? Visibility.Visible : Visibility.Hidden;
            public Thickness PathMargin
                => new Thickness(((Host == BuildHost.Windows) ? 22 : 2), 0, 2, 0);
            public FontWeight FontWeight
                => IsDefault ? FontWeights.Bold : FontWeights.Normal;

            public static ImageSource ExplorerIcon => StaticLazy.Get(() =>
                ExplorerIcon, () => GetExplorerIcon());

            public State State { get; set; } = State.Unknown;
            public bool RowVisible => State != State.Removed;
        }

        private bool IsValid { get; set; }

        Field FocusedField { get; set; }

        List<Row> Rows => Lazy.Get(() => Rows, () => new List<Row>());
        public IEnumerable<Row> Versions => Rows.TakeWhile(item => !item.LastRow);

        public void UpdateVersions(IEnumerable<Row> versions)
        {
            Rows.Clear();
            Rows.AddRange(versions);
            Rows.Add(new Row { LastRow = true });
            DataGrid.ItemsSource = Rows;
            IsValid = true;
            FocusedField = null;
            Validate(true);
            Rows.ForEach(item => item.State = State.Existing);
        }

        public IEnumerable<string> GetErrorMessages()
        {
            Validate(true);
            return Versions
                .Where(v => v.State != State.Removed)
                .SelectMany(v => v.Fields.Values.Select(f => f.ValidationError))
                .Where(s => !string.IsNullOrEmpty(s))
                .Distinct();
        }

        void Validate(bool mustRefresh)
        {
            ////////////////////////
            // Validate cell values
            string previousValidation;
            bool wasValid = IsValid;
            IsValid = true;
            foreach (var version in Versions) {
                if (!version.State.HasFlag(State.Modified))
                    continue;

                //////////////////////
                // Default validation
                if (version.State.HasFlag((State)Column.IsDefault)) {
                    previousValidation = version.FieldDefault.ValidationError;
                    version.FieldDefault.ValidationError = null;
                    if (version.IsDefault && version.Host != BuildHost.Windows) {
                        version.FieldDefault.ValidationError = "Default version: Host must be Windows";
                        IsValid = false;
                    }
                    if (previousValidation != version.FieldDefault.ValidationError)
                        mustRefresh = true;
                }

                ///////////////////
                // Name validation
                if (version.State.HasFlag((State)Column.VersionName)) {
                    previousValidation = version.FieldVersionName.ValidationError;
                    version.FieldVersionName.ValidationError = null;
                    if (string.IsNullOrEmpty(version.VersionName)) {
                        version.FieldVersionName.ValidationError = "Name cannot be empty";
                        IsValid = false;
                    } else if (Versions.Where(otherVersion => otherVersion != version
                        && otherVersion.VersionName == version.VersionName).Any()) {
                        version.FieldVersionName.ValidationError = "Duplicate version names";
                        IsValid = false;
                    }
                    if (previousValidation != version.FieldVersionName.ValidationError)
                        mustRefresh = true;
                }

                ///////////////////
                // Host validation
                if (version.State.HasFlag((State)Column.Host)) {
                    previousValidation = version.FieldHost.ValidationError;
                    version.FieldHost.ValidationError = null;
                    if (version.IsDefault && version.Host != BuildHost.Windows) {
                        version.FieldHost.ValidationError = "Default version: Host must be Windows";
                        IsValid = false;
                    }
                    if (previousValidation != version.FieldHost.ValidationError)
                        mustRefresh = true;
                }

                ///////////////////
                // Path validation
                if (version.State.HasFlag((State)Column.Path)) {
                    previousValidation = version.FieldPath.ValidationError;
                    version.FieldPath.ValidationError = null;
                    if (string.IsNullOrEmpty(version.Path)) {
                        version.FieldPath.ValidationError = "Path cannot be empty";
                        IsValid = false;
                    } else if (version.Host == BuildHost.Windows) {
                        var path = NormalizePath(version.Path);
                        if (!Directory.Exists(path)) {
                            version.FieldPath.ValidationError = "Path does not exist";
                            IsValid = false;
                        } else if (!File.Exists(Path.Combine(path, "qmake.exe"))) {
                            version.FieldPath.ValidationError = "Cannot find qmake.exe";
                            IsValid = false;
                        }
                    }
                    if (previousValidation != version.FieldPath.ValidationError)
                        mustRefresh = true;
                }

                ///////////////////////
                // Compiler validation
                if (version.State.HasFlag((State)Column.Compiler)) {
                    previousValidation = version.FieldCompiler.ValidationError;
                    version.FieldCompiler.ValidationError = null;
                    if (string.IsNullOrEmpty(version.Compiler)) {
                        version.FieldCompiler.ValidationError = "Compiler cannot be empty";
                        IsValid = false;
                    }
                    if (previousValidation != version.FieldCompiler.ValidationError)
                        mustRefresh = true;
                }
            }

            //////////////////////////////////////
            // Refresh versions table if required
            mustRefresh |= (wasValid != IsValid);
            if (mustRefresh) {
                // Reset bindings
                foreach (var version in Versions) {
                    foreach (var field in version.Fields.Values) {
                        field.Control = null;
                        field.Cell = null;
                    }
                }
                // Refresh UI
                DataGrid.Items.Refresh();
            }
        }

        static readonly Brush InvalidCellBackground = new DrawingBrush
        {
            TileMode = TileMode.Tile,
            Viewport = new Rect(0.0, 0.0, 10.0, 10.0),
            ViewportUnits = BrushMappingMode.Absolute,
            Viewbox = new Rect(0.0, 0.0, 10.0, 10.0),
            ViewboxUnits = BrushMappingMode.Absolute,
            Drawing = new DrawingGroup
            {
                Children = new DrawingCollection
                {
                    new GeometryDrawing
                    {
                        Brush = Brushes.Red,
                        Geometry = new RectangleGeometry(new Rect(5, 0, 5, 10))
                    }
                }
            },
            Transform = new RotateTransform
            {
                Angle = -135.0,
                CenterX = 0.5,
                CenterY = 0.5
            },
            Opacity = 0.25
        };

        void Control_Loaded(object sender, RoutedEventArgs e)
        {
            if (sender is Control control && GetBinding(control) is Row version) {
                if (version.LastRow)
                    return;
                if (string.IsNullOrEmpty(control.Name) || !control.Name.TryCast(out Column column))
                    return;

                var field = version.Fields[column];
                field.Control = control;
                field.Cell = FindContainingCell(control);
                if (field.Cell != null) {
                    field.Cell.Background =
                        field.IsValid ? Brushes.Transparent : InvalidCellBackground;
                }
                if (field == FocusedField)
                    control.Focus();
                if (control is TextBox textBox && field.SelectionStart >= 0)
                    textBox.Select(field.SelectionStart, 0);
            }
        }

        void ComboBox_Loaded(object sender, RoutedEventArgs e)
        {
            if (sender is ComboBox comboBox && GetBinding(comboBox) is Row version) {
                comboBox.IsEnabled = false;
                var hosts = GetValues<string>(typeof(BuildHost));
                comboBox.ItemsSource = hosts;
                comboBox.Text = version.Host.Cast<string>();
                comboBox.SelectedIndex = (int)version.Host;
                comboBox.IsEnabled = true;
            }
            Control_Loaded(sender, e);
        }

        void Control_GotFocus(object sender, RoutedEventArgs e)
        {
            if (sender is Control control && GetBinding(control) is Row version) {
                if (string.IsNullOrEmpty(control.Name) || !control.Name.TryCast(out Column column))
                    return;

                var field = version.Fields[column];
                if (field.Control != control)
                    return;
                FocusedField = field;
            }
        }

        void Control_LostFocus(object sender, RoutedEventArgs e)
        {
            if (sender is Control control && GetBinding(control) is Row version) {
                if (string.IsNullOrEmpty(control.Name) || !control.Name.TryCast(out Column column))
                    return;

                var field = version.Fields[column];
                if (field != FocusedField || field.Control != control)
                    return;
                FocusedField = null;
            }
        }

        void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (sender is TextBox textBox && GetBinding(textBox) is Row version) {
                if (string.IsNullOrEmpty(textBox.Name) || !textBox.Name.TryCast(out Column column))
                    return;

                var field = version.Fields[column];
                if (field.Control != textBox)
                    return;
                field.SelectionStart = textBox.SelectionStart;
            }
        }

        void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (sender is TextBox textBox && GetBinding(textBox) is Row version) {
                if (string.IsNullOrEmpty(textBox.Name) || !textBox.Name.TryCast(out Column column))
                    return;

                var field = version.Fields[column];
                if (field == null
                    || field.Control != textBox
                    || field.Value == textBox.Text)
                    return;

                field.SelectionStart = textBox.SelectionStart;
                field.Value = textBox.Text;
                version.State |= State.Modified | (State)column;

                Validate(false);
            }
        }

        void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (sender is ComboBox comboBox && GetBinding(comboBox) is Row version) {
                if (!comboBox.IsEnabled || comboBox.SelectedIndex < 0)
                    return;
                if (string.IsNullOrEmpty(comboBox.Name) || !comboBox.Name.TryCast(out Column column))
                    return;

                string comboBoxValue = comboBox.Items[comboBox.SelectedIndex] as string;
                var field = version.Fields[column];
                if (field == null
                    || field.Control != comboBox
                    || field.Value == comboBoxValue)
                    return;

                field.Value = comboBoxValue;
                version.State |= State.Modified | (State)Column.Host;

                bool mustRefresh = false;
                if (version.Host != BuildHost.Windows && version.Compiler == "msvc") {
                    version.Compiler = "g++";
                    version.FieldCompiler.SelectionStart = version.Compiler.Length;
                    version.State |= (State)Column.Compiler;
                    mustRefresh = true;
                } else if (version.Host == BuildHost.Windows && version.Compiler != "msvc") {
                    version.Compiler = "msvc";
                    version.FieldCompiler.SelectionStart = version.Compiler.Length;
                    version.State |= (State)Column.Compiler;
                    mustRefresh = true;
                }

                Validate(mustRefresh);
            }
        }

        static void SetDefaultState(ref Row version, bool value)
        {
            version.IsDefault = value;
            version.State |= State.Modified | (State)Column.IsDefault;
        }

        void Default_Click(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox checkBox && GetBinding(checkBox) is Row version) {
                var defaultVersion = Rows.FirstOrDefault(row => row.IsDefault);
                if (defaultVersion != null)
                    SetDefaultState(ref defaultVersion, false);
                SetDefaultState(ref version, true);
                Validate(true);
            }
        }

        void Add_Click(object sender, RoutedEventArgs e)
        {
            var version = new Row()
            {
                IsDefault = !Versions.Any(x => x.State != State.Removed),
                Host = BuildHost.Windows,
                Path = "",
                Compiler = "msvc",
                LastRow = false,
                State = State.Modified | (State)Column.VersionName | (State)Column.Host
                                       | (State)Column.Path | (State)Column.Compiler
            };
            if (version.IsDefault)
                version.State |= (State)Column.IsDefault;
            Rows.Insert(Rows.Count - 1, version);
            FocusedField = version.FieldVersionName;
            Validate(true);
        }

        void Remove_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && GetBinding(button) is Row version) {
                version.State = State.Removed;
                if (version.IsDefault) {
                    var first = Versions.FirstOrDefault(x => x.State != State.Removed);
                    if (first != null)
                        SetDefaultState(ref first, true);
                }
                Validate(true);
            }
        }

        static string NormalizePath(string path)
        {
            if (string.IsNullOrEmpty(path))
                return path;

            return Path.GetFullPath(new Uri(path).LocalPath)
                .TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
                .ToUpperInvariant();
        }

        void Explorer_Click(object sender, RoutedEventArgs e)
        {
            if (sender is Button button && GetBinding(button) is Row version) {
                var openFileDialog = new OpenFileDialog()
                {
                    AddExtension = false,
                    CheckFileExists = true,
                    CheckPathExists = true,
                    Filter = "qmake Executable|qmake.exe",
                    Title = "Qt VS Tools - Select qmake.exe"
                };
                if (openFileDialog.ShowDialog() == true) {
                    var qmakePath = openFileDialog.FileName;
                    var qmakeDir = Path.GetDirectoryName(qmakePath);
                    var previousPath = NormalizePath(version.Path);
                    if (Path.GetFileName(qmakeDir)
                        .Equals("bin", StringComparison.InvariantCultureIgnoreCase)) {
                        qmakeDir = Path.GetDirectoryName(qmakeDir);
                        version.Path = qmakeDir;
                    } else {
                        version.Path = qmakePath;
                    }

                    if (previousPath != NormalizePath(version.Path))
                        version.State |= State.Modified | (State)Column.Path;

                    if (string.IsNullOrEmpty(version.VersionName)) {
                        version.VersionName = string.Format("{0}_{1}",
                            Path.GetFileName(Path.GetDirectoryName(qmakeDir)),
                            Path.GetFileName(qmakeDir))
                            .Replace(" ", "_");
                        version.State |= State.Modified | (State)Column.VersionName;
                    }

                    Validate(true);
                }
            }
        }

        static ImageSource GetExplorerIcon()
        {
            var pathWindowsExplorer = string.Format(@"{0}\explorer.exe",
                Environment.GetFolderPath(Environment.SpecialFolder.Windows));

            NativeAPI.SHFILEINFO shellFileInfo = new NativeAPI.SHFILEINFO();
            NativeAPI.SHGetFileInfo(pathWindowsExplorer,
                0, ref shellFileInfo, Marshal.SizeOf(shellFileInfo),
                NativeAPI.SHGFI.Icon | NativeAPI.SHGFI.SmallIcon);
            if (shellFileInfo.hIcon == IntPtr.Zero)
                return null;

            var iconImageSource = Imaging.CreateBitmapSourceFromHIcon(
                shellFileInfo.hIcon, Int32Rect.Empty,
                BitmapSizeOptions.FromEmptyOptions());

            NativeAPI.DestroyIcon(shellFileInfo.hIcon);
            return iconImageSource;
        }

        static object GetBinding(FrameworkElement control)
        {
            if (control == null
                || control.BindingGroup == null
                || control.BindingGroup.Items == null
                || control.BindingGroup.Items.Count == 0) {
                return null;
            }
            return control.BindingGroup.Items[0];
        }

        static DataGridCell FindContainingCell(DependencyObject control)
        {
            while (control != null) {
                if (control is ContentPresenter contentPresenter
                    && contentPresenter.Parent is DataGridCell cell) {
                    return cell;
                }
                control = VisualTreeHelper.GetParent(control);
            }
            return null;
        }
    }
}