Files
cms_thermo_active/Client2020/BrowserTools/BrowserJSObject.cs
T
2020-10-23 16:23:59 +02:00

530 lines
16 KiB
C#

using CefSharp;
using Client.Config;
using Client.Config.SubModels;
using Client2020.BrowserTools.Models;
using Client2020.BrowserTools.Models.Errors;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
using System.Windows.Forms;
namespace Client2020.BrowserTools
{
public class BrowserJSObject
{
private Form mainForm;
private static readonly string[] _validExtensions = { ".json", ".rcp", ".tpl" };
//private static readonly string[] _validExtensions = { "", ".txt", ".cnc", ".cn", ".cno", ".ini", ".mpf", ".spf", ".tap", ".anc", ".iso" };
private static readonly string[] _validImages = { ".svg" };
private static string jobPath = "";
private static Dictionary<string, IntPtr> _editorOpened = new Dictionary<string, IntPtr>();
public static string RECENT_FOLDER_KEY = "RECENT";
private const string THERMO_RECIPE_PATH = @"C:\CMS\Recipes";
private const string CMS_PATH = @"C:\CMS";
#region CONSTRUCTOR_METHOD
public BrowserJSObject(Form f)
{
mainForm = f;
}
#endregion CONSTRUCTOR_METHOD
#region FORM_BEHAVIOUR_METHODS
public void minimizeForm()
{
//Invoke method if is needed or call the method in STD mode
if (mainForm.InvokeRequired)
mainForm.Invoke((MethodInvoker)delegate ()
{
mainForm.WindowState = FormWindowState.Minimized;
});
else
{
mainForm.WindowState = FormWindowState.Minimized;
}
}
// Maximize Main Window
public void maximizeForm()
{
//Invoke method if is needed or call the method in STD mode
if (mainForm.InvokeRequired)
mainForm.Invoke((MethodInvoker)delegate ()
{
mainForm.WindowState = FormWindowState.Maximized;
});
else
{
mainForm.WindowState = FormWindowState.Maximized;
}
}
// Close Main Window
public void closeForm()
{
//If the mainform is disposed do nothing
if (mainForm.IsDisposed)
return;
//Invoke method if is needed or call the method in STD mode
Application.Exit();
}
#endregion FORM_BEHAVIOUR_METHODS
#region NC_BEHAVIOUR_METHODS
public void setNcWindowState(int val)
{
}
public int getNcWindowState()
{
return 0;
}
public string getScreenBase64()
{
return "";
}
#endregion NC_BEHAVIOUR_METHODS
#region CHROMIUM_METHODS
// Get the Version of Chromium
public string getChromiumVersion()
{
return Cef.ChromiumVersion + " (" + Application.ProductVersion + ")";
}
#endregion CHROMIUM_METHODS
#region STEP_METHODS
// Get the ID of STEP Client
public int getClientID()
{
return Config.ConnectionConfig.Id;
}
public void forceStepFocus()
{
}
public void forceNcFocus()
{
}
public void forceProdFocus()
{
}
// Get the option of virtual Keyb configured
private bool isVirtualKeybConfigured()
{
return Config.ClientConfig.ShowVirtualKeyboard;
}
// Get the option of virtual Keyb configured
private bool isHMIenabled()
{
return Config.VendorHmiConfig.Enabled;
}
// Get the option of PROD Enabled
private bool isPRODenabled()
{
return Config.ProdSoftwareConfig.Enabled;
}
// Get the SCM option
private bool isSCMVisualStyle()
{
return Config.ClientConfig.IsSCM;
}
private string openExternalBrowser(string proc)
{
Process.Start(proc);
return "";
}
#endregion STEP_METHODS
#region PROCESSES_METHODS
// Read all configured processes
public string getConfiguredProcesses()
{
return JsonConvert.SerializeObject(Config.ExtSoftwaresConfig.Where(X => X.inMainMenuBar == false));
}
// Read all configured processes in main menu
public string getConfiguredProcessesInMainMenu()
{
return JsonConvert.SerializeObject(Config.ExtSoftwaresConfig.Where(X => X.inMainMenuBar == true));
}
// Start a new process
public void startNewProcess(string proc)
{
Thread t = new Thread(new ParameterizedThreadStart(OpenNew));
t.Start(proc);
}
// Open the last window or Start a new process
public void openOrStartProcess(string proc)
{
Thread t = new Thread(new ParameterizedThreadStart(OpenStartNew));
t.Start(proc);
}
// Function used in Thread
private void OpenStartNew(object id)
{
Software sft = Config.ExtSoftwaresConfig.FirstOrDefault(X => X.id == (string)id);
if (sft != null && File.Exists(sft.path))
{
Process[] p = Process.GetProcessesByName(Path.GetFileNameWithoutExtension(sft.path)).OrderByDescending(X => X.StartTime).ToArray();
if (p.Count() > 0 && p[0].MainWindowHandle != IntPtr.Zero)
NcWindow.ForceExtFocus(p[0].MainWindowHandle, 0, 0, 0, 0);
else
{
ProcessStartInfo PS = new ProcessStartInfo(sft.path, sft.arguments);
PS.WorkingDirectory = new FileInfo(sft.path).Directory.FullName;
Process.Start(PS);
}
}
}
// Function used in Thread
private void OpenNew(object id)
{
Software sft = Config.ExtSoftwaresConfig.FirstOrDefault(X => X.id == (string)id);
if (sft != null)
{
ProcessStartInfo PS = new ProcessStartInfo(sft.path, sft.arguments);
PS.WorkingDirectory = new FileInfo(sft.path).Directory.FullName;
Process.Start(PS);
}
}
#endregion PROCESSES_METHODS
#region FILESYSTEM_METHODS
public string getOSdriveList()
{
List<Drive> drivelist = new List<Drive>();
if (Directory.Exists(THERMO_RECIPE_PATH))
{
drivelist.Add(new Drive()
{
Name = ElaborateName("Recipes", "", DriveType.Unknown),
Path = THERMO_RECIPE_PATH + "\\",
Type = "SPFO"
});
}
return JsonConvert.SerializeObject(drivelist);
}
// Read all files in directory
public string getFileList(string p)
{
List<FileModel> filelist = new List<FileModel>();
if (p != RECENT_FOLDER_KEY && !Directory.Exists(p))
{
return (JsonConvert.SerializeObject(new ErrorContainer("file_not_exists")));
}
try
{
if (p == RECENT_FOLDER_KEY)
{
filelist = new List<FileModel>();
}
else
{
// Add directories
foreach (string item in Directory.GetDirectories(p))
{
filelist.Add(new FileModel
{
Name = Path.GetFileName(item),
AbsolutePath = Path.GetFullPath(item),
Path = Path.GetFullPath(item),
IsDirectory = true,
FileExist = true,
IsMain = false
});
}
// Add files
foreach (string item in Directory.GetFiles(p))
{
if (_validExtensions.Contains(Path.GetExtension(item).ToLower()))
{
bool isJob = false;
filelist.Add(new FileModel
{
Name = Path.GetFileName(item),
AbsolutePath = Path.GetFullPath(item),
Path = Path.GetFullPath(item),
IsDirectory = false,
IsJob = isJob,
IsMain = false,
FileExist = true
});
}
}
}
}
catch { }
return (JsonConvert.SerializeObject(filelist));
}
// Read info of a file
public string getProgramInfo(string p)
{
string imagePath, imageDirectory;
if (!File.Exists(p))
{
return (JsonConvert.SerializeObject(new InfoFile()));
}
FileInfo f = new FileInfo(p);
InfoFile file = new InfoFile
{
Name = f.Name,
CreationDate = f.CreationTime,
LastModDate = f.LastAccessTime,
AbsolutePath = p,
CanEdit = !f.IsReadOnly
};
imagePath = Path.GetFileNameWithoutExtension(p);
imageDirectory = Path.GetDirectoryName(p);
file.SheetX = "";
file.SheetY = "";
file.SheetZ = "";
file.Annotation = "";
try
{
dynamic content = JsonConvert.DeserializeObject(File.ReadAllText(p));
if (content != null && content.RecipeParameters != null)
{
if (content.RecipeParameters.general_sizes_sheet_dim_x != null)
file.SheetX = content.RecipeParameters.general_sizes_sheet_dim_x;
if (content.RecipeParameters.general_sizes_sheet_dim_y != null)
file.SheetY = content.RecipeParameters.general_sizes_sheet_dim_y;
if (content.RecipeParameters.general_sizes_sheet_thickness != null)
file.SheetZ = content.RecipeParameters.general_sizes_sheet_thickness;
if (content.recipeNotes != null)
file.Annotation = content.recipeNotes;
}
foreach (string ext in _validImages)
{
if (File.Exists(imageDirectory + "/" + imagePath + ext))
{
if (ext.ToLower().Equals(".svg"))
file.PreviewBase64 = File.ReadAllText(imageDirectory + "/" + imagePath + ext);
else
file.PreviewBase64 = "data:image/" + ext + ";base64," + Convert.ToBase64String(File.ReadAllBytes(imageDirectory + "/" + imagePath + ext));
break;
}
}
}
catch (Exception ex)
{
}
return (JsonConvert.SerializeObject(file));
}
public string duplicateRecipe(string p1, string p2)
{
string oldFile = CMS_PATH + "\\" + p1 + ".rcp";
string newFile = CMS_PATH + "\\" + p2 + ".rcp";
string oldImage = CMS_PATH + "\\" + p1 + ".svg";
string newImage = CMS_PATH + "\\" + p2 + ".svg";
if (!File.Exists(oldFile))
{
return (JsonConvert.SerializeObject(new ErrorContainer("file_not_found")));
}
if (File.Exists(newFile))
{
return (JsonConvert.SerializeObject(new ErrorContainer("file_already_exists")));
}
try
{
File.Copy(oldFile, newFile, true);
if (File.Exists(oldImage))
{
File.Copy(oldImage, newImage, true);
}
}
catch (Exception ex)
{
return(JsonConvert.SerializeObject(new ErrorContainer("cannot_copy_file")));
}
return "";
}
public string getAllRecipeDirectories()
{
List<string> dirs = this.DirSearch(THERMO_RECIPE_PATH);
for (int i = 0; i < dirs.Count; i++)
{
dirs[i] = dirs[i].Remove(0, CMS_PATH.Length + 1);
}
return(JsonConvert.SerializeObject(dirs));
}
public string deleteFile(string p)
{
FileAttributes attr = File.GetAttributes(p);
if (!File.Exists(p) || attr.HasFlag(FileAttributes.Directory))
{
return (JsonConvert.SerializeObject(new ErrorContainer("file_not_found")));
}
if (attr.HasFlag(FileAttributes.ReadOnly))
{
return (JsonConvert.SerializeObject(new ErrorContainer("file_not_editable")));
}
try
{
File.Delete(p);
string images = Path.ChangeExtension(p, "svg");
if (File.Exists(images))
{
File.Delete(images);
}
}
catch (Exception ex)
{
return (JsonConvert.SerializeObject(new ErrorContainer("cannot_delete_file")));
}
return "";
}
public string deleteFolder(string p)
{
FileAttributes attr = File.GetAttributes(p);
if (!Directory.Exists(p) || !attr.HasFlag(FileAttributes.Directory))
{
return (JsonConvert.SerializeObject(new ErrorContainer("directory_not_found")));
}
if (attr.HasFlag(FileAttributes.ReadOnly))
{
return (JsonConvert.SerializeObject(new ErrorContainer("directory_not_editable")));
}
try
{
Directory.Delete(p, true);
}
catch (Exception ex)
{
return (JsonConvert.SerializeObject(new ErrorContainer("cannot_delete_directory")));
}
return "";
}
public string createFolder(string path)
{
if (Directory.Exists(path))
{
return (JsonConvert.SerializeObject(new ErrorContainer("directory_already_exists")));
}
try
{
Directory.CreateDirectory(path);
}
catch (Exception ex)
{
return (JsonConvert.SerializeObject(new ErrorContainer("cannot_delete_directory")));
}
return "";
}
// Private functions
private string ElaborateType(DriveType type)
{
switch (type)
{
case DriveType.Fixed: return "HD";
case DriveType.Removable: return "USB";
case DriveType.Network: return "NTW";
}
return "SPFO";
}
private string ElaborateName(string name, string letter, DriveType type)
{
var retName = "";
if (!string.IsNullOrWhiteSpace(name))
retName = name;
else
{
switch (type)
{
case DriveType.Fixed: retName = "Hard_Disk"; break;
case DriveType.Removable: retName = "Usb_Disk"; break;
case DriveType.Network: retName = "Netword_Disk"; break;
default: retName = "Undefined"; break;
}
}
if (!string.IsNullOrWhiteSpace(letter))
retName = retName + " (" + letter + ")";
return retName;
}
private List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
files.Add(sDir);
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
return files;
}
#endregion FILESYSTEM_METHODS
}
}