-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathSettings.cs
More file actions
472 lines (419 loc) · 19.2 KB
/
Copy pathSettings.cs
File metadata and controls
472 lines (419 loc) · 19.2 KB
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
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Jupyter;
using R;
using SAS;
using Stata;
using StatTag.Core.Models;
using StatTag.Models;
namespace StatTag
{
public sealed partial class Settings : Form
{
private const string ExecutableFileFilter = "Application Executable|*.exe";
private const string LogFileFilter = "Log File|*.log";
private const string BlankValueLabelTemplate =
"Note: The current document is set to use [BLANK_VALUE] for missing values. Changes made here will affect new documents, but not the current document. The setting for the current document can be changed under \"Document Properties\".";
public Core.Models.UserSettings Properties { get; set; }
private LogManager Logger { get; set; }
private DocumentManager Manager { get; set; }
private bool StataAutomationEnabledOnEntry { get; set; }
private SystemDetails SystemInformation { get; set; }
/// <summary>
/// If set when the dialog closes, this signals that a configuration change took place and
/// that StatTag should refresh the system information cache.
/// </summary>
public bool RefreshSystemInformation { get; private set; }
public Settings(Core.Models.UserSettings properties, DocumentManager manager, SystemDetails sysInfo)
{
AutoScaleMode = AutoScaleMode.None;
InitializeComponent();
Properties = properties;
Manager = manager;
SystemInformation = sysInfo;
MinimumSize = Size;
Logger = new LogManager();
UIUtility.SetDialogTitle(this);
RefreshSystemInformation = false;
tabSettings.AutoSize = true;
tabGeneral.AutoSize = true;
tabLogging.AutoSize = true;
tabStata.AutoSize = true;
StataAutomationEnabledOnEntry = Stata.StataAutomation.IsAutomationEnabled();
chkStataAutomation.Checked = StataAutomationEnabledOnEntry;
UpdateStataSettingsUI();
UpdateRSettingsUI(SystemInformation.RSupport);
}
private void cmdStataLocation_Click(object sender, EventArgs e)
{
var stataPath = UIUtility.GetOpenFileName(ExecutableFileFilter);
if (!string.IsNullOrWhiteSpace(stataPath))
{
txtStataLocation.Text = stataPath;
}
}
private void Settings_Load(object sender, EventArgs e)
{
txtStataLocation.Text = Properties.StataLocation;
chkEnableLogging.Checked = Properties.EnableLogging;
txtLogLocation.Text = Properties.LogLocation;
chkRunCodeOnOpen.Checked = Properties.RunCodeOnOpen;
txtMaxLogSize.Value = ((int)(Properties.GetValueInRange(Properties.MaxLogFileSize,
Core.Models.UserSettings.MaxLogFileSizeMin, Core.Models.UserSettings.MaxLogFileSizeMax,
Core.Models.UserSettings.MaxLogFileSizeDefault) / (Constants.BytesToMegabytesConversion * 1.0)));
txtMaxLogFiles.Value = Properties.GetValueInRange(Properties.MaxLogFiles,
Core.Models.UserSettings.MaxLogFilesMin, Core.Models.UserSettings.MaxLogFilesMax,
Core.Models.UserSettings.MaxLogFilesDefault);
missingValueSettings1.SetMissingValuesSelection(Properties.RepresentMissingValues);
missingValueSettings1.SetCustomMissingValueString(Properties.CustomMissingValue);
missingValueSettings1.ValueChanged += missingValueSettings_Changed;
UpdateLoggingControls();
UpdateMissingValueControls();
}
private void missingValueSettings_Changed(object sender, EventArgs e)
{
UpdateMissingValueControls();
}
private void UpdateMissingValueControls()
{
var documentMetadata = Manager.LoadMetadataFromCurrentDocument(false);
var customMissingValue = missingValueSettings1.GetCustomMissingValueString();
var representMissingValues = missingValueSettings1.GetMissingValuesSelection();
lblEmptyValueWarning.Visible = false;
if (documentMetadata != null && (!representMissingValues.Equals(documentMetadata.RepresentMissingValues)
|| (representMissingValues.Equals(Constants.MissingValueOption.CustomValue) && !customMissingValue.Equals(documentMetadata.CustomMissingValue))))
{
lblEmptyValueWarning.Text = BlankValueLabelTemplate.Replace("[BLANK_VALUE]", documentMetadata.GetMissingValueReplacementAsString());
lblEmptyValueWarning.Visible = true;
}
}
/// <summary>
/// Utility method to confirm that the Stata EXE path provided by the user is valid. If not,
/// inform the user of this.
/// </summary>
/// <returns>true if the file exists, or false otherwise</returns>
private bool CheckStataFilePath()
{
if (File.Exists(txtStataLocation.Text))
{
return true;
}
MessageBox.Show(this,
string.Format("The Stata executable could not be found at {0}.", txtStataLocation.Text),
UIUtility.GetAddInName(), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return false;
}
private bool EnableStataAutomation()
{
try
{
if (!CheckStataFilePath())
{
return false;
}
Cursor = Cursors.WaitCursor;
// We are going to first try to unregister the automation API, if it was set up.
// If this fails, we don't show an error message and will just move on trying to enable
// automation.
Stata.StataAutomation.UnregisterAutomationAPI(txtStataLocation.Text);
if (!Stata.StataAutomation.RegisterAutomationAPI(txtStataLocation.Text))
{
ShowStataCommandError("enable");
return false;
}
ShowStataCommandSuccess("enabled");
}
catch (Exception)
{
return false;
}
finally
{
Cursor = Cursors.Default;
}
RefreshSystemInformation = true;
return true;
}
private bool DisableStataAutomation()
{
try
{
if (!CheckStataFilePath())
{
return false;
}
if (DialogResult.Yes !=
MessageBox.Show(this,
"***WARNING: Disabling Stata Automation will reset your Stata user preferences.\r\n\r\nAlso, if you disable Stata Automation, StatTag will no longer work with Stata results.\r\n\r\nAre you sure you want to proceed?",
UIUtility.GetAddInName(), MessageBoxButtons.YesNo))
{
return false;
}
Cursor = Cursors.WaitCursor;
if (!Stata.StataAutomation.UnregisterAutomationAPI(txtStataLocation.Text))
{
ShowStataCommandError("disable");
return false;
}
ShowStataCommandSuccess("disabled");
}
finally
{
Cursor = Cursors.Default;
}
RefreshSystemInformation = true;
return true;
}
private void ShowStataCommandError(string action)
{
Cursor = Cursors.Default;
MessageBox.Show(
string.Format(
"There was an error trying to {0} the Stata Automation API.\r\nMore information about Stata Automation can be found at: http://www.stata.com/automation",
action), UIUtility.GetAddInName(), MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
}
private void ShowStataCommandSuccess(string action)
{
Cursor = Cursors.Default;
MessageBox.Show(
string.Format(
"The Stata Automation API has been successfully {0}.",
action), UIUtility.GetAddInName());
}
private void cmdOK_Click(object sender, EventArgs e)
{
// If the Stata location has changed, and the user clicked 'OK' on this dialog, we're going to assume they
// want to enable the Stata automation API, or disable it if they unchecked the automation box.
if (!HandleStataAutomationAPIChanges())
{
DialogResult = DialogResult.None;
return;
}
Properties.StataLocation = txtStataLocation.Text;
Properties.EnableLogging = chkEnableLogging.Checked;
Properties.LogLocation = txtLogLocation.Text;
Properties.RunCodeOnOpen = chkRunCodeOnOpen.Checked;
Properties.MaxLogFileSize = ((uint)(txtMaxLogSize.Value * Constants.BytesToMegabytesConversion));
Properties.MaxLogFiles = (uint)txtMaxLogFiles.Value;
Properties.CustomMissingValue = missingValueSettings1.GetCustomMissingValueString();
Properties.RepresentMissingValues = missingValueSettings1.GetMissingValuesSelection();
if (Properties.EnableLogging && !Logger.IsValidLogPath(Properties.LogLocation))
{
UIUtility.WarningMessageBox("The debug file you have selected appears to be invalid, or you do not have rights to access it.\r\nPlease select a valid path for the debug file, or disable debugging.", null);
DialogResult = DialogResult.None;
}
}
private bool HandleStataAutomationAPIChanges()
{
// If the Stata location is empty, there's really nothing we can do. We're just going
// to accept the change and proceed. This will avoid warning the user that the file
// location "" (blank string) couldn't be found.
if (string.IsNullOrWhiteSpace(txtStataLocation.Text))
{
return true;
}
// If there was a change in the file location, and automation is still enabled, we
// need to handle unregistering and re-registering
if (chkStataAutomation.Checked && !string.Equals(Properties.StataLocation, txtStataLocation.Text))
{
return EnableStataAutomation();
}
else if (chkStataAutomation.Checked != StataAutomationEnabledOnEntry)
{
if (chkStataAutomation.Checked)
{
return EnableStataAutomation();
}
else
{
return DisableStataAutomation();
}
}
// No changes, so everything is fine.
return true;
}
private void chkEnableLogging_CheckedChanged(object sender, EventArgs e)
{
UpdateLoggingControls();
}
private void UpdateLoggingControls()
{
bool enableControls = chkEnableLogging.Checked;
cmdLogLocation.Enabled = enableControls;
txtLogLocation.Enabled = enableControls;
txtMaxLogFiles.Enabled = enableControls;
txtMaxLogSize.Enabled = enableControls;
}
private void cmdLogLocation_Click(object sender, EventArgs e)
{
var logPath = UIUtility.GetSaveFileName(LogFileFilter);
if (!string.IsNullOrWhiteSpace(logPath))
{
txtLogLocation.Text = logPath;
}
}
private void txtLogLocation_TextChanged(object sender, EventArgs e)
{
string logFilePath = txtLogLocation.Text;
if (string.IsNullOrWhiteSpace(logFilePath))
{
lblLogWarning.Text = "Please select or enter a file path";
lblLogWarning.Visible = true;
}
else
{
lblLogWarning.Visible = false;
}
}
private void chkStataAutomation_CheckedChanged(object sender, EventArgs e)
{
UpdateStataSettingsUI();
}
private void UpdateStataSettingsUI()
{
var enabled = chkStataAutomation.Checked;
txtStataLocation.Enabled = enabled;
cmdStataLocation.Enabled = enabled;
}
private void UpdateRSettingsUI(bool supported)
{
lblRSupportStatus.Text = supported ? "Enabled" : "Not detected";
lblRSupportStatus.ForeColor = supported ? Color.Green : Color.Red;
}
private void cmdInstallRSupport_Click(object sender, EventArgs e)
{
Logger.WriteMessage("Beginning installation of R support");
var result = MessageBox.Show("StatTag will attempt to install and configure the IRkernel package in R. This will make changes to your R setup. Do you wish to continue?",
UIUtility.GetAddInName(), MessageBoxButtons.YesNoCancel);
if (DialogResult.Yes != result)
{
Logger.WriteMessage("User cancelled setting up IRkernel");
LogRStatusFailure();
return;
}
LogRStatusAndLogger("Proceeding with IRkernel setup. Locating R...");
var rPath = RAutomation.DetectRPath();
if (string.IsNullOrWhiteSpace(rPath))
{
LogRStatusAndLogger("Unable to locate an R installation using the registry");
LogRStatusFailure();
return;
}
else if (!Directory.Exists(rPath))
{
LogRStatusAndLogger(string.Format("R path in registry but could not be found: {0}", rPath));
LogRStatusFailure();
return;
}
else
{
LogRStatusAndLogger(string.Format("R path found: {0}", rPath));
}
rPath = Path.Combine(rPath, "R.exe");
if (!File.Exists(rPath))
{
LogRStatusAndLogger(string.Format("Could not find R.exe at {0}", rPath));
LogRStatusFailure();
return;
}
LogRStatusAndLogger("Attempting to install IRkernel...");
var irKernelResult = RAutomation.RunRFromCommandLine(rPath, "-e \"install.packages('IRkernel', repos = 'https://cloud.r-project.org')\"");
if (irKernelResult.Result)
{
LogRStatusAndLogger("Successfully installed (or confirmed installation of) IRkernel");
LogRStatusAndLogger(irKernelResult.Details);
}
else
{
LogRStatusAndLogger("Failed to install IRkernel. Please see the StatTag User Guide for more instructions on how to set up R support.");
LogRStatusAndLogger(irKernelResult.Details);
LogRStatusFailure();
return;
}
LogRStatusAndLogger("Detecting Jupyter...");
string embeddedJupyterPath = null;
var jupyterStatus = JupyterAutomation.DetectJupyter();
if (jupyterStatus.Result)
{
LogRStatusAndLogger("Found Jupyter: " + jupyterStatus.Details);
}
else
{
LogRStatusAndLogger("Did not find a Jupyter. Using embedded environment");
embeddedJupyterPath = JupyterAutomation.ExtractPythonToTempFolder();
if (string.IsNullOrWhiteSpace(embeddedJupyterPath))
{
LogRStatusAndLogger("Failed to use embedded Python/Jupyter environment. No available Jupyter environment to use for IRkernel setup.");
LogRStatusAndLogger("Failed to configure IRkernel. Please see the StatTag User Guide for more instructions on how to set up R support.");
return;
}
else
{
LogRStatusAndLogger(string.Format("Using embedded Jupyter at: {0}", embeddedJupyterPath));
}
}
LogRStatusAndLogger("Attempging to configure IRkernel...");
//var embeddedJupyterPath = "";
//var executingAssembly = System.Reflection.Assembly.GetExecutingAssembly();
//if (Uri.IsWellFormedUriString(executingAssembly.CodeBase, UriKind.Absolute))
//{
// var codeBasePath = Path.GetDirectoryName(new Uri(executingAssembly.CodeBase).LocalPath);
// var embeddedJupyterBase = Path.Combine(codeBasePath, "python-embed");
// if (Directory.Exists(embeddedJupyterBase))
// {
// LogRStatusAndLogger(string.Format("Using embedded Jupyter at: {0}", embeddedJupyterBase));
// embeddedJupyterPath = string.Format("{0};{1}",
// embeddedJupyterBase,
// Path.Combine(embeddedJupyterBase, "Scripts"));
// }
//}
// The embeddedJupyterPath contains the base path for where the files exist. We need to expand this for adding
// to the PATH variable to include the base as well as the \Scripts subfolder.
var embeddedJupyterExpandedPaths = string.Format("{0};{0}\\Scripts", embeddedJupyterPath);
var configResult = RAutomation.RunRFromCommandLine(rPath, "-e \"IRkernel::installspec()\"", embeddedJupyterExpandedPaths);
if (configResult.Result)
{
LogRStatusAndLogger("Successfully configured IRkernel");
UpdateRSettingsUI(true);
RefreshSystemInformation = true;
}
else
{
LogRStatusAndLogger("Failed to configure IRkernel. Please see the StatTag User Guide for more instructions on how to set up R support.");
LogRStatusAndLogger(configResult.Details);
LogRStatusFailure();
}
// If we used a temporary Jupyter/Python environment to do this, clean it up.
if (!string.IsNullOrWhiteSpace(embeddedJupyterPath))
{
JupyterAutomation.CleanupTempPythonFolder(embeddedJupyterPath);
}
}
/// <summary>
/// Utility function to write a final "failed" message during R support setup
/// </summary>
private void LogRStatusFailure()
{
LogRStatusAndLogger("\r\n*** SETUP FAILED ***");
}
/// <summary>
/// Utility function to log the same text both to the dialog text field, as well as the log (if enabled)
/// </summary>
/// <param name="text"></param>
private void LogRStatusAndLogger(string text)
{
txtRSupportProgress.Text += text + "\r\n";
txtRSupportProgress.SelectionStart = txtRSupportProgress.Text.Length;
txtRSupportProgress.ScrollToCaret();
Logger.WriteMessage(text);
}
}
}