Наша сборка Qt VS Tools
giy
2022-06-13 175679ae608f0b295d761588d332f635b21bdf30
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
/****************************************************************************
**
** Copyright (C) 2020 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;
using QtVsTools.Common;
 
namespace QtVsTools.Options
{
    using static EnumExt;
 
    public enum BuildHost
    {
        [String("Windows")] Windows,
        [String("Linux SSH")] LinuxSSH,
        [String("Linux WSL")] LinuxWSL,
    }
 
    public partial class QtVersionsTable : UserControl
    {
        public QtVersionsTable()
        {
            InitializeComponent();
        }
 
        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
        {
            public enum FieldNames { IsDefault, VersionName, Host, Path, Compiler }
 
            public Dictionary<FieldNames, Field> _Fields;
            public Dictionary<FieldNames, Field> Fields => _Fields
                ?? (_Fields = GetValues<FieldNames>()
                    .Select(field => new KeyValuePair<FieldNames, Field>(field, null))
                    .ToDictionary(keyValue => keyValue.Key, keyValue => keyValue.Value));
 
            public Field FieldDefault => Fields[FieldNames.IsDefault]
                ?? (Fields[FieldNames.IsDefault] = new Field());
            public bool IsDefault
            {
                get => (FieldDefault.Value == true.ToString());
                set => FieldDefault.Value = value.ToString();
            }
 
            public Field FieldVersionName => Fields[FieldNames.VersionName]
                ?? (Fields[FieldNames.VersionName] = new Field());
            public string VersionName
            {
                get => FieldVersionName.Value;
                set => FieldVersionName.Value = value;
            }
 
            public Field FieldHost => Fields[FieldNames.Host]
                ?? (Fields[FieldNames.Host] = new Field());
            public BuildHost Host
            {
                get => FieldHost.Value.Cast(defaultValue: BuildHost.Windows);
                set => FieldHost.Value = value.Cast<string>();
            }
 
            public Field FieldPath => Fields[FieldNames.Path]
                ?? (Fields[FieldNames.Path] = new Field());
            public string Path
            {
                get => FieldPath.Value;
                set => FieldPath.Value = value;
            }
 
            public Field FieldCompiler => Fields[FieldNames.Compiler]
                ?? (Fields[FieldNames.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 RowVisibility
                => 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;
            public static ImageSource ExplorerIcon => _ExplorerIcon
                ?? (_ExplorerIcon = GetExplorerIcon());
        }
 
        public bool IsValid { get; private set; }
 
        Field FocusedField { get; set; }
 
        List<Row> _Rows;
        List<Row> Rows => _Rows ?? (_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);
        }
 
        public IEnumerable<string> GetErrorMessages()
        {
            Validate(true);
            return Versions
                .SelectMany(v => v.Fields.Values.Select(f => f.ValidationError))
                .Where(s => !string.IsNullOrEmpty(s))
                .Distinct();
        }
 
        void Validate(bool mustRefresh)
        {
            /////////////////////////
            // Automatic cell values
            foreach (var version in Versions) {
                if (version.Host != BuildHost.Windows && version.Compiler == "msvc") {
                    version.Compiler = "g++";
                    version.FieldCompiler.SelectionStart = version.Compiler.Length;
                    mustRefresh = true;
                } else if (version.Host == BuildHost.Windows && version.Compiler != "msvc") {
                    version.Compiler = "msvc";
                    version.FieldCompiler.SelectionStart = version.Compiler.Length;
                    mustRefresh = true;
                }
            }
 
            ////////////////////////
            // Validate cell values
            string previousValidation;
            bool wasValid = IsValid;
            IsValid = true;
            foreach (var version in Versions) {
 
                //////////////////////
                // Default validation
                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
                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
                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
                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 && !Directory.Exists(version.Path)) {
                    version.FieldPath.ValidationError = "Path does not exist";
                    IsValid = false;
                }
                if (previousValidation != version.FieldPath.ValidationError)
                    mustRefresh = true;
 
                ///////////////////////
                // Compiler validation
                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;
 
                Row.FieldNames field;
                if (string.IsNullOrEmpty(control.Name) || !control.Name.TryCast(out field))
                    return;
 
                var fieldBinding = version.Fields[field];
                fieldBinding.Control = control;
                fieldBinding.Cell = FindContainingCell(control);
                if (fieldBinding.Cell != null) {
                    fieldBinding.Cell.Background =
                        fieldBinding.IsValid ? Brushes.Transparent : InvalidCellBackground;
                }
                if (fieldBinding == FocusedField)
                    control.Focus();
                if (control is TextBox textBox && fieldBinding.SelectionStart >= 0)
                    textBox.Select(fieldBinding.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) {
                Row.FieldNames field;
                if (string.IsNullOrEmpty(control.Name) || !control.Name.TryCast(out field))
                    return;
                var fieldBinding = version.Fields[field];
                if (fieldBinding.Control != control)
                    return;
                FocusedField = fieldBinding;
            }
        }
 
        void Control_LostFocus(object sender, RoutedEventArgs e)
        {
            if (sender is Control control && GetBinding(control) is Row version) {
                Row.FieldNames field;
                if (string.IsNullOrEmpty(control.Name) || !control.Name.TryCast(out field))
                    return;
                var fieldBinding = version.Fields[field];
                if (fieldBinding != FocusedField || fieldBinding.Control != control)
                    return;
                FocusedField = null;
            }
        }
 
        void TextBox_SelectionChanged(object sender, RoutedEventArgs e)
        {
            if (sender is TextBox textBox && GetBinding(textBox) is Row version) {
                Row.FieldNames field;
                if (string.IsNullOrEmpty(textBox.Name) || !textBox.Name.TryCast(out field))
                    return;
                var fieldBinding = version.Fields[field];
                if (fieldBinding.Control != textBox)
                    return;
                fieldBinding.SelectionStart = textBox.SelectionStart;
            }
        }
 
        void TextBox_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (sender is TextBox textBox && GetBinding(textBox) is Row version) {
                Row.FieldNames field;
                if (string.IsNullOrEmpty(textBox.Name) || !textBox.Name.TryCast(out field))
                    return;
                var fieldBinding = version.Fields[field];
                if (fieldBinding == null
                    || fieldBinding.Control != textBox
                    || fieldBinding.Value == textBox.Text)
                    return;
                fieldBinding.SelectionStart = textBox.SelectionStart;
                fieldBinding.Value = textBox.Text;
                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;
                string comboBoxValue = comboBox.Items[comboBox.SelectedIndex] as string;
                string controlName = comboBox.Name;
                Row.FieldNames field;
                if (string.IsNullOrEmpty(controlName) || !controlName.TryCast(out field))
                    return;
                var fieldBinding = version.Fields[field];
                if (fieldBinding == null
                    || fieldBinding.Control != comboBox
                    || fieldBinding.Value == comboBoxValue)
                    return;
                fieldBinding.Value = comboBoxValue;
                Validate(false);
            }
        }
 
        void Default_Click(object sender, RoutedEventArgs e)
        {
            if (sender is CheckBox checkBox && GetBinding(checkBox) is Row version) {
                var defaultVersion = Rows.Where(row => row.IsDefault).FirstOrDefault();
                if (defaultVersion != null)
                    defaultVersion.IsDefault = false;
                version.IsDefault = true;
                Validate(true);
            }
        }
 
        void Add_Click(object sender, RoutedEventArgs e)
        {
            var version = new Row()
            {
                IsDefault = !Versions.Any(),
                Host = BuildHost.Windows,
                Path = "",
                Compiler = "msvc",
                LastRow = false
            };
            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) {
                Rows.Remove(version);
                if (version.IsDefault && Versions.Any())
                    Versions.First().IsDefault = true;
                Validate(true);
            }
        }
 
        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);
                    if (Path.GetFileName(qmakeDir)
                        .Equals("bin", StringComparison.InvariantCultureIgnoreCase)) {
                        qmakeDir = Path.GetDirectoryName(qmakeDir);
                        version.Path = qmakeDir;
                    } else {
                        version.Path = qmakePath;
                    }
                    if (string.IsNullOrEmpty(version.VersionName)) {
                        version.VersionName = string.Format("{0}_{1}",
                            Path.GetFileName(Path.GetDirectoryName(qmakeDir)),
                            Path.GetFileName(qmakeDir))
                            .Replace(" ", "_");
                    }
                    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;
        }
    }
}