aboutsummaryrefslogtreecommitdiffstats
path: root/QtVsTools.Core/Messages.cs
blob: ab010b33771d1585ef4145d5afafe1903dd2ea23 (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
// Copyright (C) 2025 The Qt Company Ltd.
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only WITH Qt-GPL-exception-1.0

using System;
using System.Collections.Concurrent;
using System.Text;
using System.Threading;
using System.Windows.Forms;
using Microsoft.VisualStudio.Shell;
using Microsoft.VisualStudio.Threading;

using static System.Environment;
using Task = System.Threading.Tasks.Task;

namespace QtVsTools.Core
{
    using Options;
    using VisualStudio;

    public static class Messages
    {
        public static bool Initialized { get; set; } = false;

        private static OutputWindowPane Pane { get; set; }

        private const string Name = "Qt VS Tools";
        private static readonly Guid PaneGuid = new("8f6a1e44-fa0b-49e5-9934-1c050555350e");

        /// <summary>
        /// Show a message on the output pane.
        /// </summary>
        public static void Print(string text,
            bool clear = false, bool activate = false, bool trim = true)
        {
            msgQueue.Enqueue(new Msg
            {
                Clear = clear,
                Text = trim ? text.Trim(' ', '\t', '\r', '\n') : text,
                Activate = activate
            });
            FlushMessages();
        }

        public static void Log(this Exception exception, bool clear = false, bool activate = false)
        {
            msgQueue.Enqueue(new Msg
            {
                Clear = clear,
                Text = ExceptionToString(exception),
                Activate = activate
            });
            FlushMessages();
        }

        /// <summary>
        /// Activates the message pane of the Qt VS Tools extension.
        /// </summary>
        public static void ActivateMessagePane()
        {
            msgQueue.Enqueue(new Msg
            {
                Activate = true
            });
            FlushMessages();
        }

        static async Task OutputWindowPane_ActivateAsync()
        {
            await OutputWindowPane_InitAsync();
            await Pane?.ActivateAsync();
        }

        private static string ExceptionToString(Exception exception)
        {
            return $"An exception ({exception.GetType().Name}) occurred.\r\n"
                   + $"Message:\r\n   {exception.Message}\r\n"
                   + $"Stack Trace:\r\n   {exception.StackTrace.Trim()}\r\n";
        }

        private const string ErrorString = "The following error occurred:";
        private static readonly string WarningString = "Warning:" + NewLine;

        public static void DisplayCriticalErrorMessage(string msg)
        {
            MessageBox.Show(ErrorString + NewLine + msg,
                Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void DisplayErrorMessage(Exception e)
        {
            MessageBox.Show(ExceptionToString(e),
                Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void DisplayErrorMessage(string msg)
        {
            MessageBox.Show(ErrorString + NewLine + msg,
                Name, MessageBoxButtons.OK, MessageBoxIcon.Error);
        }

        public static void DisplayWarningMessage(Exception e, string solution)
        {
            MessageBox.Show(WarningString
                + ExceptionToString(e)
                + NewLine + NewLine + "To solve this problem:" + NewLine
                + solution,
                Name, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        public static void DisplayWarningMessage(string msg)
        {
            MessageBox.Show(WarningString +
                msg,
                Name, MessageBoxButtons.OK, MessageBoxIcon.Warning);
        }

        public static void ClearPane()
        {
            msgQueue.Enqueue(new Msg
            {
                Clear = true
            });
            FlushMessages();
        }

        static async Task OutputWindowPane_ClearAsync()
        {
            await OutputWindowPane_InitAsync();
            await Pane?.ClearAsync();
        }

        class Msg
        {
            public bool Clear { get; set; }
            public string Text { get; set; }
            public bool Activate { get; set; }
        }

        static readonly ConcurrentQueue<Msg> msgQueue = new();

        private static async Task OutputWindowPane_InitAsync()
        {
            try {
                Pane ??= await OutputWindowPane.CreateAsync(Name, PaneGuid);
            } catch (Exception ex) {
                System.Diagnostics.Debug.WriteLine(ex);
            }
        }

        public static JoinableTaskFactory JoinableTaskFactory { get; set; }

        static readonly object staticCriticalSection = new();
        static Task FlushTask { get; set; }
        static EventWaitHandle MessageReady { get; set; }

        static void FlushMessages()
        {
            lock (staticCriticalSection) {
                if (FlushTask == null) {
                    MessageReady = new EventWaitHandle(false, EventResetMode.AutoReset);
                    FlushTask = Task.Run(async () =>
                    {
                        while (VsServiceProvider.Instance == null)
                            await Task.Delay(1000, VsShellUtilities.ShutdownToken);
                        while (!VsShellUtilities.ShutdownToken.IsCancellationRequested) {
                            await Task.Delay(Initialized ? 100 : 1000);
                            if (!await MessageReady.ToTask(3000))
                                continue;
                            bool clear = false;
                            bool activate = false;
                            var msgText = new StringBuilder();
                            while (!msgQueue.IsEmpty) {
                                if (!msgQueue.TryDequeue(out var msg)) {
                                    await Task.Yield();
                                    continue;
                                }
                                if (msg is null)
                                    continue;
                                clear |= msg.Clear;
                                activate |= msg.Activate;
                                if (!string.IsNullOrEmpty(msg.Text))
                                    msgText.AppendLine(msg.Text);
                            }
                            if (clear)
                                await OutputWindowPane_ClearAsync();
                            if (msgText.Length > 0)
                                await OutputWindowPane_PrintAsync(msgText.ToString());
                            if (activate && QtOptionsPage.AutoActivatePane)
                                await OutputWindowPane_ActivateAsync();
                        }
                    });
                }
            }
            MessageReady.Set();
        }

        static async Task OutputWindowPane_PrintAsync(string text)
        {
            await OutputWindowPane_InitAsync();
            await Pane.PrintAsync(text);
        }
    }
}