summaryrefslogtreecommitdiffstats
path: root/win/CS/HandBrakeWPF/ViewModels/LogViewModel.cs
blob: 907b33a403414b4cd3020715e370cb79f76d3cab (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
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="LogViewModel.cs" company="HandBrake Project (http://handbrake.fr)">
//   This file is part of the HandBrake source code - It may be used under the terms of the GNU General Public License.
// </copyright>
// <summary>
//   Defines the LogViewModel type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace HandBrakeWPF.ViewModels
{
    using System;
    using System.Collections.Generic;
    using System.ComponentModel;
    using System.Diagnostics;
    using System.IO;
    using System.Linq;
    using System.Text;

    using Caliburn.Micro;

    using HandBrake.Worker.Logging.Models;

    using HandBrakeWPF.Properties;
    using HandBrakeWPF.Services.Interfaces;
    using HandBrakeWPF.Services.Logging.EventArgs;
    using HandBrakeWPF.Services.Logging.Interfaces;
    using HandBrakeWPF.Services.Queue.Interfaces;
    using HandBrakeWPF.Utilities;
    using HandBrakeWPF.ViewModels.Interfaces;

    using Clipboard = System.Windows.Clipboard;
    using ILog = Services.Logging.Interfaces.ILog;
    using LogEventArgs = Services.Logging.EventArgs.LogEventArgs;

    public class LogViewModel : ViewModelBase, ILogViewModel
    {
        private readonly IErrorService errorService;
        private readonly ILogInstanceManager logInstanceManager;
        private readonly IQueueService queueService;
        private readonly object readLockObject = new object();

        private ILog logService;
        private StringBuilder log = new StringBuilder();
        private long lastReadIndex;

        private string selectedLogFile;

        public LogViewModel(IErrorService errorService, ILogInstanceManager logInstanceManager, IQueueService queueService)
        {
            this.errorService = errorService;
            this.logInstanceManager = logInstanceManager;
            this.queueService = queueService;
            this.Title = Resources.LogViewModel_Title;
        }

        public event EventHandler<LogEventArgs> LogMessageReceived;

        public string ActivityLog => this.log.ToString();

        public BindingList<string> LogFiles { get; private set; }

        public string SelectedLogFile
        {
            get => this.selectedLogFile;
            set
            {
                if (value == this.selectedLogFile)
                {
                    return;
                }

                this.selectedLogFile = value;
                this.NotifyOfPropertyChange(() => this.SelectedLogFile);

                this.ChangeLogFileView();
            }
        }

        public void OpenLogDirectory()
        {
            string logDir = DirectoryUtilities.GetLogDirectory();
            string windir = Environment.GetEnvironmentVariable("WINDIR");
            Process prc = new Process { StartInfo = { FileName = windir + @"\explorer.exe", Arguments = logDir } };
            prc.Start();
        }

        public void CopyLog()
        {
            try
            {
                Clipboard.SetDataObject(this.ActivityLog, true);
            }
            catch (Exception exc)
            {
                this.errorService.ShowError(Resources.Clipboard_Unavailable, Resources.Clipboard_Unavailable_Solution, exc);
            }
        }

        protected override void OnActivate()
        {
            this.logInstanceManager.NewLogInstanceRegistered += this.LogInstanceManager_NewLogInstanceRegistered;
            this.queueService.QueueChanged += this.QueueService_QueueChanged;

            this.CollectLogFiles(null);
            
            base.OnActivate();
        }

        protected override void OnDeactivate(bool close)
        {
            if (this.logService != null)
            {
                this.logService.MessageLogged -= this.LogService_MessageLogged;
                this.logService.LogReset -= this.LogService_LogReset;
            }

            this.SelectedLogFile = null;
            this.logInstanceManager.NewLogInstanceRegistered -= this.LogInstanceManager_NewLogInstanceRegistered;
            this.queueService.QueueChanged -= this.QueueService_QueueChanged;

            base.OnDeactivate(close);
        }

        protected virtual void OnLogMessageReceived(LogEventArgs e)
        {
            var onLogMessageReceived = this.LogMessageReceived;
            onLogMessageReceived?.Invoke(this, e);
        }

        private void ChangeLogFileView()
        {
            if (this.logService != null)
            {
                this.logService.MessageLogged -= this.LogService_MessageLogged;
                this.logService.LogReset -= this.LogService_LogReset;
            }

            if (this.SelectedLogFile == null)
            {
                return;
            }

            this.logService = this.logInstanceManager.GetLogInstance(this.SelectedLogFile);
            string logDir = DirectoryUtilities.GetLogDirectory();
            string logFile = Path.Combine(logDir, this.selectedLogFile);

            // This is not an active log, so read from disk.
            if (this.logService == null)
            {
                try
                {
                    if (File.Exists(logFile))
                    {
                        this.log.Clear();
                        using (StreamReader logReader = new StreamReader(logFile))
                        {
                            string logContent = logReader.ReadToEnd();
                            this.log.AppendLine(logContent);
                        }
                    } 
                    else
                    {
                        this.log.Clear();
                        this.log.AppendLine("Sorry, The log file was not found.");
                    }
                }
                catch (Exception exc)
                {
                    Debug.WriteLine(exc);
                    this.log.AppendLine(exc.ToString());
                }

                this.OnLogMessageReceived(null);
                this.NotifyOfPropertyChange(() => this.ActivityLog);
            }

            // Active in-progress log, read from the log service.
            if (this.logService != null)
            {
                this.logService.MessageLogged += this.LogService_MessageLogged;
                this.logService.LogReset += LogService_LogReset;

                // Refresh the Log Display
                this.log.Clear();
                foreach (LogMessage logMessage in this.logService.GetLogMessages())
                {
                    this.log.AppendLine(logMessage.Content);
                    this.lastReadIndex = logMessage.MessageIndex;

                    if (this.lastReadIndex > logMessage.MessageIndex)
                    {
                        throw new Exception("Log Message Index Error");
                    }
                }

                this.OnLogMessageReceived(null);
                this.NotifyOfPropertyChange(() => this.ActivityLog);
            }
        }

        private void LogService_LogReset(object sender, EventArgs e)
        {
            this.log.Clear();
            this.lastReadIndex = 0;

            foreach (LogMessage logMessage in this.logService.GetLogMessages())
            {
                this.log.AppendLine(logMessage.Content);
                this.lastReadIndex = logMessage.MessageIndex;

                if (this.lastReadIndex > logMessage.MessageIndex)
                {
                    throw new Exception("Log Message Index Error");
                }
            }

            this.NotifyOfPropertyChange(() => this.ActivityLog);
            this.OnLogMessageReceived(null);
        }

        private void LogService_MessageLogged(object sender, LogEventArgs e)
        {
            if (this.lastReadIndex < e.Log.MessageIndex)
            {
                Execute.OnUIThreadAsync(() =>
                        {
                            this.lastReadIndex = e.Log.MessageIndex;
                            this.log.AppendLine(e.Log.Content);
                            this.OnLogMessageReceived(e);
                            this.NotifyOfPropertyChange(() => this.ActivityLog);
                        });
            }
        }

        private void LogInstanceManager_NewLogInstanceRegistered(object sender, LogFileEventArgs e)
        {
            this.CollectLogFiles(e.FileName);
        }
        
        private void QueueService_QueueChanged(object sender, EventArgs e)
        {
            this.CollectLogFiles(null);
        }

        private void CollectLogFiles(string filename)
        {
            lock (readLockObject)
            {
                BindingList<string> activeLogs = new BindingList<string>(this.logInstanceManager.GetLogFiles());
                BindingList<string> logfiles = new BindingList<string>();

                // Add Inactive Logs First.
                foreach (string logFile in this.queueService.GetLogFilePaths())
                {
                    logfiles.Add(Path.GetFileName(logFile));
                }

                // Add active logs second.
                foreach (var log in activeLogs)
                {
                    logfiles.Add(log);
                }

                this.LogFiles = logfiles;
                this.NotifyOfPropertyChange(() => this.LogFiles);

                if (!string.IsNullOrEmpty(filename))
                {
                    this.SelectedLogFile = this.LogFiles.FirstOrDefault(c => c.Equals(filename, StringComparison.InvariantCultureIgnoreCase));
                }
                else
                {
                    this.SelectedLogFile = this.LogFiles.LastOrDefault(c => !c.Contains("activity_log_main"));
                }

                if (this.SelectedLogFile == null)
                {
                    this.SelectedLogFile = this.LogFiles.LastOrDefault();
                }
            }
        }
    }
}