Commit 3b75ee9d authored by Thomas's avatar Thomas
Browse files

Add possibility to reopen edited config file

parent 85b5a479
...@@ -11,7 +11,7 @@ namespace pEp.DPE ...@@ -11,7 +11,7 @@ namespace pEp.DPE
internal class DistributedPolicyEngine : IDistributedPolicyEngine internal class DistributedPolicyEngine : IDistributedPolicyEngine
{ {
private readonly static string DPE_FOLDER = Path.Combine(Globals.PEPUserFolder, "DPE"); private readonly static string DPE_FOLDER = Path.Combine(Globals.PEPUserFolder, "DPE");
public readonly static string DPE_BACKUP_LOCATION = Path.Combine(DistributedPolicyEngine.DPE_FOLDER, "temp"); public readonly static string DPE_TEMP_LOCATION = Path.Combine(DistributedPolicyEngine.DPE_FOLDER, "temp");
private const string PATCH_EXTENSION = ".patch"; private const string PATCH_EXTENSION = ".patch";
private const string PATCH_MESSAGE_SUBJECT = "Configuration changes"; private const string PATCH_MESSAGE_SUBJECT = "Configuration changes";
public const string DPE_MESSAGE_CLASS = "IPM.Note.DPE"; public const string DPE_MESSAGE_CLASS = "IPM.Note.DPE";
......
namespace pEp.UI.Models
{
public class ConfigFile
{
public string FileName { get; }
public string TempFileName { get; }
public string Diff { get; }
public ConfigFile(string fileName, string tempFileName, string diff)
{
this.FileName = fileName;
this.TempFileName = tempFileName;
this.Diff = diff;
}
}
}
...@@ -97,7 +97,6 @@ namespace pEp.UI.Models ...@@ -97,7 +97,6 @@ namespace pEp.UI.Models
{ {
if (dialogResult == System.Windows.Forms.DialogResult.OK) if (dialogResult == System.Windows.Forms.DialogResult.OK)
{ {
patchDialog.Patch.CreationDate = DateTime.UtcNow;
Globals.ThisAddIn.DistributedPolicyEngine.Suggest(patchDialog.Patch, me); Globals.ThisAddIn.DistributedPolicyEngine.Suggest(patchDialog.Patch, me);
} }
} }
......
...@@ -18,17 +18,33 @@ namespace pEp.UI.ViewModels ...@@ -18,17 +18,33 @@ namespace pEp.UI.ViewModels
{ {
#region Fields #region Fields
private bool _IsCommitMessageValid = false; private RelayCommand _AddOrEditFileCommand = null;
private bool _IsDiffValid = false; private bool _IsCommitMessageValid = false;
private bool _IsValid = false; private bool _IsDiffValid = false;
private RelayCommand _LoadFromFileCommand = null; private bool _IsValid = false;
private Tuple<string, string, string> _SelectedFile = null; private ConfigFile _SelectedFile = null;
private FlowDocument _VisibleDiff = null; private FlowDocument _VisibleDiff = null;
#endregion #endregion
#region Properties #region Properties
/// <summary>
/// Gets the command to load the diff from file.
/// </summary>
public RelayCommand AddOrEditFileCommand
{
get
{
if (this._AddOrEditFileCommand == null)
{
this._AddOrEditFileCommand = new RelayCommand(this.AddOrEditFile);
}
return this._AddOrEditFileCommand;
}
}
/// <summary> /// <summary>
/// Command to cancel the dialog. /// Command to cancel the dialog.
/// </summary> /// </summary>
...@@ -131,26 +147,10 @@ namespace pEp.UI.ViewModels ...@@ -131,26 +147,10 @@ namespace pEp.UI.ViewModels
} }
} }
/// <summary>
/// Gets the command to load the diff from file.
/// </summary>
public RelayCommand LoadFromFileCommand
{
get
{
if (this._LoadFromFileCommand == null)
{
this._LoadFromFileCommand = new RelayCommand(this.AddFile);
}
return this._LoadFromFileCommand;
}
}
/// <summary> /// <summary>
/// Gets the collection of config files that are being modified. /// Gets the collection of config files that are being modified.
/// </summary> /// </summary>
public ObservableCollection<Tuple<string, string, string>> ConfigFiles { get; } = new ObservableCollection<Tuple<string, string, string>>(); public ObservableCollection<ConfigFile> ConfigFiles { get; } = new ObservableCollection<ConfigFile>();
/// <summary> /// <summary>
/// The command to accept the patch dialog. /// The command to accept the patch dialog.
...@@ -170,7 +170,7 @@ namespace pEp.UI.ViewModels ...@@ -170,7 +170,7 @@ namespace pEp.UI.ViewModels
/// <summary> /// <summary>
/// Gets the currently selected file. /// Gets the currently selected file.
/// </summary> /// </summary>
public Tuple<string, string, string> SelectedFile public ConfigFile SelectedFile
{ {
get => this._SelectedFile; get => this._SelectedFile;
set set
...@@ -240,22 +240,44 @@ namespace pEp.UI.ViewModels ...@@ -240,22 +240,44 @@ namespace pEp.UI.ViewModels
/// Adds a new file to the list of modified config files. /// Adds a new file to the list of modified config files.
/// </summary> /// </summary>
/// <param name="parameter">The command parameter.</param> /// <param name="parameter">The command parameter.</param>
private void AddFile(object parameter) private void AddOrEditFile(object parameter)
{ {
// Create the dialog to select the key file string fileName = parameter as string;
OpenFileDialog openFileDialog = new OpenFileDialog if (string.IsNullOrEmpty(fileName))
{ {
CheckFileExists = true, // Create the dialog to select the key file
CheckPathExists = true, OpenFileDialog openFileDialog = new OpenFileDialog
Filter = "All files|*.*", {
Multiselect = false CheckFileExists = true,
}; CheckPathExists = true,
Filter = "All files|*.*",
Multiselect = false
};
// Import the key file and set the key as default // Import the key file and set the key as default
if (openFileDialog.ShowDialog() == true) if (openFileDialog.ShowDialog() == true)
{
fileName = openFileDialog.FileName;
}
}
if (!string.IsNullOrEmpty(fileName))
{ {
this.EditFileAndCreateDiff(openFileDialog.FileName); this.EditFileAndCreateDiff(fileName);
} }
this.ValidatePatch();
}
/// <summary>
/// Closes this window.
/// </summary>
/// <param name="dialogResult">The dialog result.</param>
private new void Close(bool? dialogResult)
{
// Delete temporary directory and close
this.DeleteTempDirectory();
base.Close(dialogResult);
} }
/// <summary> /// <summary>
...@@ -277,6 +299,24 @@ namespace pEp.UI.ViewModels ...@@ -277,6 +299,24 @@ namespace pEp.UI.ViewModels
this.Close(true); this.Close(true);
} }
/// <summary>
/// Deletes the temporary directory.
/// </summary>
private void DeleteTempDirectory()
{
try
{
if (Directory.Exists(DistributedPolicyEngine.DPE_TEMP_LOCATION))
{
Directory.Delete(DistributedPolicyEngine.DPE_TEMP_LOCATION, true);
}
}
catch (Exception ex)
{
Log.Error("DeleteTempDirectory: Error deleting temporary directory. " + ex);
}
}
/// <summary> /// <summary>
/// Creates a diff from two files. /// Creates a diff from two files.
/// </summary> /// </summary>
...@@ -349,7 +389,7 @@ namespace pEp.UI.ViewModels ...@@ -349,7 +389,7 @@ namespace pEp.UI.ViewModels
} }
else if (newLines[i].Type == ChangeType.Inserted) else if (newLines[i].Type == ChangeType.Inserted)
{ {
block.Add("-" + oldLines[i].Text); block.Add("+" + newLines[i].Text);
unchangedCount = 0; unchangedCount = 0;
} }
else if (newLines[i].Type == ChangeType.Modified) else if (newLines[i].Type == ChangeType.Modified)
...@@ -373,6 +413,10 @@ namespace pEp.UI.ViewModels ...@@ -373,6 +413,10 @@ namespace pEp.UI.ViewModels
{ {
block.Insert(0, " " + newLines[index].Text); block.Insert(0, " " + newLines[index].Text);
} }
else
{
break;
}
} }
index++; index++;
newFileIndex = newLines[index].Position ?? 1; newFileIndex = newLines[index].Position ?? 1;
...@@ -399,106 +443,6 @@ namespace pEp.UI.ViewModels ...@@ -399,106 +443,6 @@ namespace pEp.UI.ViewModels
return diff.TrimEnd('\n'); return diff.TrimEnd('\n');
} }
//private string CreateDiff(string fileNameA, string fileNameB)
//{
// if (!(File.Exists(fileNameA) && File.Exists(fileNameB)))
// {
// Log.ErrorAndFailInDebugMode("CreateDiff: Input file doesn't exist.");
// return null;
// }
// string fileA, fileB;
// try
// {
// fileA = File.ReadAllText(fileNameA);
// fileB = File.ReadAllText(fileNameB);
// }
// catch (Exception ex)
// {
// Log.Error("CreateDiff: Error reading input file. " + ex);
// return null;
// }
// string diff = $"---a/{ fileNameB }\n+++b/{ fileNameB }\n";
// DiffPaneModel diffPaneModel = InlineDiffBuilder.Diff(fileA, fileB);
// List<DiffPiece> lines = diffPaneModel.Lines;
// List<DiffPiece> block = new List<DiffPiece>();
// for (int i = 0; i < lines.Count; i++)
// {
// if (lines[i].Type == ChangeType.Deleted || lines[i].Type == ChangeType.Inserted)
// {
// if (block.Count == 0)
// {
// int index = i - 3;
// do
// {
// if (index < 0)
// {
// continue;
// }
// if (lines[index].Type == ChangeType.Unchanged)
// {
// block.Add(lines[index]);
// }
// } while (++index < i);
// }
// block.Add(lines[i]);
// }
// else if (block.Count > 0)
// {
// block.Add(lines[i]);
// int index = 0;
// while ((++i < lines.Count) &&
// (++index < 3))
// {
// if (lines[i].Type == ChangeType.Unchanged)
// {
// block.Add(lines[i]);
// }
// else
// {
// break;
// }
// }
// if ((index == 3) || (i == lines.Count))
// {
// diff += $"@@ -{ block.First().Position },{ block.Last().Position } +{1},{1} @@\n";
// foreach (var diffPiece in block)
// {
// switch (diffPiece.Type)
// {
// case ChangeType.Unchanged:
// diff += $" { diffPiece.Text }\n";
// break;
// case ChangeType.Deleted:
// diff += $"-{ diffPiece.Text }\n";
// break;
// case ChangeType.Inserted:
// diff += $"+{ diffPiece.Text }\n";
// break;
// case ChangeType.Imaginary:
// case ChangeType.Modified:
// default:
// Log.ErrorAndFailInDebugMode("CreateDiff: Untreated diff piece.");
// break;
// }
// }
// block = new List<DiffPiece>();
// }
// }
// }
// return diff.TrimEnd('\n');
//}
/// <summary> /// <summary>
/// Opens the given file to edit and creates a diff once the editor is closed. /// Opens the given file to edit and creates a diff once the editor is closed.
/// </summary> /// </summary>
...@@ -508,17 +452,21 @@ namespace pEp.UI.ViewModels ...@@ -508,17 +452,21 @@ namespace pEp.UI.ViewModels
try try
{ {
// Get the temp file that will actually be edited // Get the temp file that will actually be edited
string tempFileName; string tempFileName, originalFileName;
if ((this.ConfigFiles.First(cf => cf.Item1.Equals(fileName)) is Tuple<string, string, string> configFile) && if ((this.ConfigFiles.FirstOrDefault(cf => cf.FileName.Equals(fileName)) is ConfigFile configFile) &&
(string.IsNullOrEmpty(configFile.Item2) == false)) (string.IsNullOrEmpty(configFile.TempFileName) == false))
{ {
tempFileName = configFile.Item2; tempFileName = configFile.TempFileName;
originalFileName = tempFileName + ".orig";
File.Copy(tempFileName, fileName, true);
} }
else else
{ {
tempFileName = Path.Combine(DistributedPolicyEngine.DPE_BACKUP_LOCATION, Path.GetFileName(fileName) + ".orig"); tempFileName = Path.Combine(DistributedPolicyEngine.DPE_TEMP_LOCATION, Path.GetFileName(fileName));
Directory.CreateDirectory(DistributedPolicyEngine.DPE_BACKUP_LOCATION); originalFileName = tempFileName + ".orig";
File.Copy(fileName, tempFileName); Directory.CreateDirectory(DistributedPolicyEngine.DPE_TEMP_LOCATION);
File.Copy(fileName, tempFileName, true);
File.Copy(fileName, originalFileName, true);
} }
// Open temp file in VS Code for the user to edit // Open temp file in VS Code for the user to edit
...@@ -527,7 +475,7 @@ namespace pEp.UI.ViewModels ...@@ -527,7 +475,7 @@ namespace pEp.UI.ViewModels
StartInfo = new ProcessStartInfo StartInfo = new ProcessStartInfo
{ {
FileName = "code", FileName = "code",
Arguments = tempFileName, Arguments = fileName,
UseShellExecute = true, UseShellExecute = true,
CreateNoWindow = true CreateNoWindow = true
} }
...@@ -535,11 +483,14 @@ namespace pEp.UI.ViewModels ...@@ -535,11 +483,14 @@ namespace pEp.UI.ViewModels
openCodeProcess.Start(); openCodeProcess.Start();
openCodeProcess.WaitForExit(); openCodeProcess.WaitForExit();
if (this.ConfigFiles.Remove(this.ConfigFiles.Where(f => (f.Item1?.Equals(fileName) == true) && f.Item2?.Equals(tempFileName) == true).First())) string diff = this.CreateDiff(originalFileName, fileName);
{ this.ConfigFiles.Remove(this.ConfigFiles.Where(f => (f.FileName?.Equals(fileName) == true) && f.TempFileName?.Equals(tempFileName) == true).FirstOrDefault());
string diff = this.CreateDiff(fileName, tempFileName); this.ConfigFiles.Add(new ConfigFile(fileName, tempFileName, diff));
this.ConfigFiles.Add(new Tuple<string, string, string>(fileName, tempFileName, diff)); File.Copy(fileName, tempFileName, true);
} File.Copy(originalFileName, fileName, true);
// Select the created diff in the UI
this.SelectedFile = this.ConfigFiles.Last();
} }
catch (Exception ex) catch (Exception ex)
{ {
...@@ -599,14 +550,14 @@ namespace pEp.UI.ViewModels ...@@ -599,14 +550,14 @@ namespace pEp.UI.ViewModels
/// <returns>The root URI</returns> /// <returns>The root URI</returns>
private string GetRootUri() private string GetRootUri()
{ {
string rootUri = this.ConfigFiles.First()?.Item1; string rootUri = this.ConfigFiles.First()?.FileName;
foreach (var modifiedFile in this.ConfigFiles) foreach (ConfigFile modifiedFile in this.ConfigFiles)
{ {
for (int i = 0; i < modifiedFile.Item1.Length; i++) for (int i = 0; i < modifiedFile.FileName.Length; i++)
{ {
if ((rootUri.Length <= i) || if ((rootUri.Length <= i) ||
(modifiedFile.Item1[i] == rootUri[i])) (modifiedFile.FileName[i] == rootUri[i]))
{ {
continue; continue;
} }
...@@ -636,9 +587,9 @@ namespace pEp.UI.ViewModels ...@@ -636,9 +587,9 @@ namespace pEp.UI.ViewModels
{ {
string diff = null; string diff = null;
foreach (var modifiedFile in this.ConfigFiles) foreach (ConfigFile modifiedFile in this.ConfigFiles)
{ {
diff += modifiedFile.Item3 + "\n"; diff += modifiedFile.Diff + "\n";
} }
return diff.TrimEnd('\n'); return diff.TrimEnd('\n');
...@@ -649,7 +600,7 @@ namespace pEp.UI.ViewModels ...@@ -649,7 +600,7 @@ namespace pEp.UI.ViewModels
/// </summary> /// </summary>
private void UpdateVisibleDiff() private void UpdateVisibleDiff()
{ {
this.VisibleDiff = this.FormatDiff(this.SelectedFile?.Item3); this.VisibleDiff = this.FormatDiff(this.SelectedFile?.Diff);
} }
/// <summary> /// <summary>
......
...@@ -48,7 +48,9 @@ ...@@ -48,7 +48,9 @@
ItemsSource="{Binding ConfigFiles}"> ItemsSource="{Binding ConfigFiles}">
<ListBox.ItemTemplate> <ListBox.ItemTemplate>
<DataTemplate> <DataTemplate>
<Label Content="{Binding Item1}" /> <ContentControl MouseDoubleClick="ListBoxItem_MouseDoubleClick">
<Label Content="{Binding FileName}" />
</ContentControl>
</DataTemplate> </DataTemplate>
</ListBox.ItemTemplate> </ListBox.ItemTemplate>
</ListBox> </ListBox>
...@@ -57,7 +59,7 @@ ...@@ -57,7 +59,7 @@
<Button Content="Add file" <Button Content="Add file"
Margin="5" Margin="5"
Style="{StaticResource StyleButtonGray}" Style="{StaticResource StyleButtonGray}"
Command="{Binding LoadFromFileCommand}"/> Command="{Binding AddOrEditFileCommand}"/>
<Button Content="Remove file" <Button Content="Remove file"
Margin="5" Margin="5"
Style="{StaticResource StyleButtonGray}" Style="{StaticResource StyleButtonGray}"
......
using System.Windows.Controls; using pEp.UI.Models;
using pEp.UI.ViewModels;
using System.Windows.Controls;
using System.Windows.Input;
namespace pEp.UI.Views namespace pEp.UI.Views
{ {
...@@ -7,9 +10,21 @@ namespace pEp.UI.Views ...@@ -7,9 +10,21 @@ namespace pEp.UI.Views
/// </summary> /// </summary>
public partial class PatchDialogView : UserControl public partial class PatchDialogView : UserControl
{ {
/// <summary>
/// Primary constructor.
/// </summary>
public PatchDialogView() public PatchDialogView()
{ {
InitializeComponent(); InitializeComponent();
} }
/// <summary>
/// Event handler for when a list box item is double-clicked.
/// </summary>
private void ListBoxItem_MouseDoubleClick(object sender, MouseButtonEventArgs e)
{
// Edit the file that is being double-clicked
(this.DataContext as PatchDialogViewModel)?.AddOrEditFileCommand?.Execute(((sender as ContentControl)?.DataContext as ConfigFile)?.FileName);
}
} }
} }
...@@ -431,6 +431,7 @@ ...@@ -431,6 +431,7 @@
<Compile Include="UI\FormRegionDPE.Designer.cs"> <Compile Include="UI\FormRegionDPE.Designer.cs">
<DependentUpon>FormRegionDPE.cs</DependentUpon> <DependentUpon>FormRegionDPE.cs</DependentUpon>
</Compile> </Compile>
<Compile Include="UI\Models\ConfigFile.cs" />
<Compile Include="UI\Models\GroupWizard.cs" /> <Compile Include="UI\Models\GroupWizard.cs" />
<Compile Include="UI\Models\CustomMessageBox.cs" /> <Compile Include="UI\Models\CustomMessageBox.cs" />
<Compile Include="UI\Models\InputMessageBox.cs" /> <Compile Include="UI\Models\InputMessageBox.cs" />
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment