// Copyright (c) UESTC. All Rights Reserved // QC // 2022/4/20 namespace Uestc.Auto6.Dso.Core { using NPOI.HSSF.UserModel; using NPOI.SS.UserModel; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Text.RegularExpressions; using Uestc.Auto6.Dso.ComModel; using Uestc.Auto6.Dso.Core.Tools; /// /// Defines the WfmFormat. /// public enum WfmFormat { [Alias("bin")] Binary, [Alias("txt")] Text, [Alias("mat")] Matlab, [Alias("xls")] Excel, [Alias("csv")] CSV, [Alias("tsv")] TSV, [Alias("wfm")] WFM, [Alias("h5")] HDF5, } /// /// Defines the PicFormat. /// public enum PicFormat { Bmp, Tiff, Gif, Png, Jpeg, } /// /// Defines the PicArea. /// public enum PicArea { FullScreen = 0, Window = 1, Application = 2 } public enum PicColor { Standard = 0, BlackWhite = 1, Reverse = 2 } public enum TxtFormat { ASCII, GB2312, UTF8, UTF32, Unicode, } /// /// Defines the . /// public class FilePrsnt : MulticastPrsnt, IFilePrsnt { /// /// Initializes a new instance of the class. /// /// The view. /// The mco. public FilePrsnt(IFileView? view, ModelCreateOptions mco = ModelCreateOptions.Dependant) { Model = mco switch { ModelCreateOptions.Dependant => DsoModel.Default.File, ModelCreateOptions.Standalone => new(), _ => throw new ArgumentException($"Argument '{nameof(mco)}' can not assign to '{nameof(ModelCreateOptions.InitializedByChild)}'."), }; Model.PropertyChanged += OnPropertyChanged; if (view != null) { view.Presenter = this; TryAddView(view); } } /// /// Gets or sets the GetImageStreamHandler. /// public static Func? GetImageStreamHandler { get; set; } public static Func? SaveLabNoteBookHandler { get; set; } /// /// Gets the DefaultPrefixName. /// public String DefaultPrefixName => Model.DefaultPrefixName; /// /// Gets or sets the FileName. /// public String FileName { get => Model.FileName; set => Model.FileName = value; } /// /// Gets or sets the IfAppendDatetime. /// public Boolean IfAppendDatetime { get => Model.IfAppendDatetime; set => Model.IfAppendDatetime = value; } /// /// Gets or sets the IsDefaultSetting. /// public Boolean IsDefaultSetting { get => Model.IsDefaultSetting; set => Model.IsDefaultSetting = value; } /// /// Gets or sets the PicFormat. /// public PicFormat PicFormat { get => Model.PicFormat; set => Model.PicFormat = value; } /// /// Gets or sets the PicPath. /// public String PicPath { get => Model.PicPath; set => Model.PicPath = value; } /// /// Gets or sets the PicRegion. /// public PicArea PicRegion { get => Model.PicRegion; set => Model.PicRegion = value; } /// /// Gets or sets the SettingLoadFullPath. /// public String SettingLoadFullPath { get => Model.SettingLoadFullPath; set => Model.SettingLoadFullPath = value; } /// /// Gets or sets the SettingSavePath. /// public String SettingSavePath { get => Model.SettingSavePath; set => Model.SettingSavePath = value; } /// /// Gets or sets the WfmFormat. /// public WfmFormat WfmFormat { get => Model.WfmFormat; set => Model.WfmFormat = value; } /// /// Gets or sets the WfmPath. /// public String WfmPath { get => Model.WfmPath; set => Model.WfmPath = value; } /// /// Gets or sets the WfmSource. /// public ChannelId WfmSource { get => Model.WfmSource; set => Model.WfmSource = value; } /// /// Gets or sets the PicColor. /// public PicColor PicColor { get => Model.PicColor; set => Model.PicColor = value; } public TxtFormat WfmTxtFormat { get => Model.WfmTxtFormat; set => Model.WfmTxtFormat = value; } /// /// Gets the Model. /// private protected override FileModel Model { get; } /// /// The GetDateTimeString. /// /// The . public static String GetDateTimeString() => "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff"); /// /// The GetImageBase64String. /// /// The . public static String? GetImageBase64String() { var ms = GetImageStreamHandler?.Invoke(PicFormat.Jpeg, PicArea.Application, PicColor.Standard); if (ms is not null) { try { var b64string = Convert.ToBase64String(ms.ToArray()); ms.Close(); return b64string; } catch (Exception e) { Logger.Error("Failed to convert image to Base64 string: " + e.ToString()); } } return null; } public static Encoding GetEncoding(TxtFormat format) { try { System.Text.Encoding.RegisterProvider(System.Text.CodePagesEncodingProvider.Instance); return format switch { TxtFormat.ASCII => Encoding.ASCII, TxtFormat.UTF8 => Encoding.UTF8, TxtFormat.UTF32 => Encoding.UTF32, TxtFormat.GB2312 => Encoding.GetEncoding("GB2312"), TxtFormat.Unicode => Encoding.Unicode, _ => Encoding.Default }; } catch (Exception e) { Logger.Error(e.ToString()); return Encoding.Default; } } /// /// The GetPicFileExtName. /// /// The pf. /// The . public static String GetPicFileExtName(PicFormat pf) => pf switch { PicFormat.Bmp => ".bmp", PicFormat.Gif => ".gif", PicFormat.Jpeg => ".jpeg", PicFormat.Png => ".png", PicFormat.Tiff => ".tiff", _ => ".dat" }; /// /// The LoadDefSetting. /// /// The . public static Boolean LoadDefSetting() => //Load Factory *.set LoadSetting(Constants.SET_DEF_PATH + "\\" + Constants.FACTORY_SET_NAME + ".set"); /// /// The LoadFromText. /// /// The fullpath. /// The reader. /// The . public static Boolean LoadFromText(String fullpath, Action reader) { try { using var fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read); using StreamReader sr = new(fs, Encoding.UTF8); reader(sr); } catch (Exception e) { Logger.Error(e.ToString()); #if DEBUG throw; #else return false; #endif } return true; } /// /// The LoadFromText. /// /// The fullpath. /// The buffer. /// The . public static Boolean LoadFromText(String fullpath, out List buffer) { buffer = new List(); try { using var fs = new FileStream(fullpath, FileMode.Open, FileAccess.Read); using StreamReader sr = new(fs, Encoding.UTF8); String? line; while ((line = sr.ReadLine()) != null) { buffer.Add(Double.Parse(line)); } } catch (Exception e) { Logger.Error(e.ToString()); #if DEBUG throw; #else return false; #endif } return true; } /// /// The LoadSetting. /// /// The fullpath. /// The . public static Boolean LoadSetting(String fullpath) { try { if (!File.Exists(fullpath)) { WeakTip.Default.Write(nameof(LoadSetting), MsgTipId.ReadingFailed); return false; } using MemoryStream memorystream = new(File.ReadAllBytes(fullpath)); var setting = BinaryConvert.Deserialize(memorystream); if (setting is null) { return false; } setting.OnDeserialized(); } catch (Exception e) { Logger.Error(e.ToString()); #if DEBUG throw; #else return false; #endif } return true; } /// /// The LoadWaveform. /// /// The fullpath. /// The id. /// The dso. /// The . public static Boolean LoadWaveform(String fullpath, ChannelId id, DsoPrsnt dso) { ReferencePrsnt? rprsnt = null; if (ReferencePrsnt.TryRead(id, fullpath, ref rprsnt)) { //Add a new reference channel presenter dso.AddChannel(id, rprsnt!); DsoPrsnt.FocusId = rprsnt!.Id; return true; } return false; } /// /// The SaveImage. /// /// The fullpath. /// The pf. /// The region. /// The . public static Boolean SaveImage(String fullpath, PicFormat pf, PicArea region, PicColor color = PicColor.Standard) { var path = Path.GetDirectoryName(fullpath); var file = Path.GetFileName(fullpath); if (String.IsNullOrEmpty(file)) { return false; } if (path?.Length == 0) { path = Directory.GetCurrentDirectory(); } return SaveImage(path!, file, pf, region, false, color); } /// /// The SaveImage. /// /// The path. /// The name. /// The pf. /// The region. /// The postfix. /// The . public static Boolean SaveImage(String path, String name, PicFormat pf, PicArea region, Boolean postfix, PicColor color = PicColor.Standard) { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); if (!Directory.Exists(path)) { Logger.Error($"Path does not exist: '{path}'"); return false; } } String fullfilename = path + "\\" + name + (postfix ? GetDateTimeString() : "") + GetPicFileExtName(pf); if (File.Exists(fullfilename)) { if (!StrongTip.Default.Show(MsgTipId.Warning, MsgTipId.FileExisted, MessageType.Warning)) { return false; } File.Delete(fullfilename); } var ms = GetImageStreamHandler?.Invoke(pf, region, color); if (ms is not null) { try { using FileStream fs = new(fullfilename, FileMode.Create, FileAccess.Write); ms.WriteTo(fs); ms.Close(); return true; } catch (Exception e) { Logger.Error("Failed to save full screen: " + e.ToString()); } } return false; } public static Boolean? SaveLabNoteBook(String LabNotePath, String LabNoteName, ChannelId channelId) => SaveLabNoteBookHandler?.Invoke(LabNotePath, LabNoteName, channelId); /// /// The SaveSetting. /// /// The fullpath. /// The . public static Boolean SaveSetting(String fullpath) { var path = Path.GetDirectoryName(fullpath); var file = Path.GetFileName(fullpath); if (String.IsNullOrEmpty(file)) { return false; } if (path?.Length == 0) { path = Directory.GetCurrentDirectory(); } return SaveSetting(path!, file, false, true); } /// /// The SaveSetting. /// /// The path. /// The name. /// The postfix. /// The dumb. /// The . public static Boolean SaveSetting(String path, String name, Boolean postfix, Boolean dumb = false) { try { if (!Directory.Exists(path)) { Directory.CreateDirectory(path); if (!Directory.Exists(path)) { Logger.Error($"Path does not exist: '{path}'"); return false; } } String fullfilename = path + "\\" + name + (postfix ? GetDateTimeString() : "") + ".set"; if (File.Exists(fullfilename)) { if (!dumb && !StrongTip.Default.Show(MsgTipId.Warning, MsgTipId.FileExisted, MessageType.Warning)) { return false; } File.Delete(fullfilename); } SysSettings settings = new(); settings.OnSerializing(); using var fs = new FileStream(fullfilename, FileMode.Create, FileAccess.Write); BinaryConvert.Serialize(settings, fs); } catch (Exception e) { Logger.Error(e.ToString()); #if DEBUG throw; #else return false; #endif } return true; } /// /// The SaveToText. /// /// The path. /// The name. /// The writer. /// The . public static Boolean SaveToText(String path, String name, Action writer) { try { String fullfilename = path + "\\" + name + ".txt"; using var fs = new FileStream(fullfilename, FileMode.Create, FileAccess.Write); using StreamWriter sw = new(fs, Encoding.UTF8); writer(sw); } catch (Exception e) { Logger.Error(e.ToString()); #if DEBUG throw; #else return false; #endif } return true; } /// /// The SaveToText. /// /// The path. /// The name. /// The buffer. /// The . public static Boolean SaveToText(String path, String name, IEnumerable buffer) { try { String fullfilename = path + "\\" + name + ".txt"; using var fs = new FileStream(fullfilename, FileMode.OpenOrCreate, FileAccess.Write); using StreamWriter sw = new(fs, Encoding.UTF8); foreach (var d in buffer) { sw.WriteLine(d); } } catch (Exception e) { Logger.Error(e.ToString()); #if DEBUG throw; #else return false; #endif } return true; } /// /// The SaveWaveByBin. /// /// The stm. /// The pkg. /// The . public static Boolean SaveWaveByBin(Stream stm, WfmPack pkg) { try { BinaryConvert.Serialize(pkg, stm); } catch (Exception e) { Logger.Error(e.ToString()); #if DEBUG throw; #else return false; #endif } return true; } /// /// The SaveWaveByCSV. /// /// The stm. /// The pkg. /// The . public static Boolean SaveWaveByCSV(Stream stm, WfmPack pkg) => SaveWaveByText(stm, pkg, (x, y) => x.ToString("E") + "," + String.Join(",", y.Select(o => o.ToString("G")))); /// /// The SaveWaveByExcel. /// /// The stm. /// The pkg. /// The . public static Boolean SaveWaveByExcel(Stream stm, WfmPack pkg) { try { HSSFWorkbook workbook = new(); ISheet sheet = workbook.CreateSheet("Sheet1"); Int32 length = pkg.Buffer.GetLength(1); Int32 wfmcnt = pkg.Buffer.GetLength(0); Double sp = pkg.Properties.TmbScale.Value * Constants.VIS_XDIVS_NUM / length; Double pos0 = pkg.Properties.TmbPosition.Index; Double time; IRow head = sheet.CreateRow(0); head.CreateCell(0).SetCellValue($"Time({pkg.Properties.TmbUnit.Prefix.ToPfxString()}{pkg.Properties.TmbUnit.Name})"); for (Int32 i = 0; i < wfmcnt; i++) { head.CreateCell(i + 1).SetCellValue($"Ampl({pkg.Properties.ChnlUnit.Prefix.ToPfxString()}{pkg.Properties.ChnlUnit.Name})"); } for (Int32 j = 0; j < length; j++) { var row = (HSSFRow)sheet.CreateRow(j + 1); time = (j - pos0) * sp + pkg.Properties.TrigErrorTime; row.CreateCell(0).SetCellValue(time); for (Int32 i = 0; i < wfmcnt; i++) { row.CreateCell(i + 1).SetCellValue(pkg.Buffer[i, j]); //if (row.GetCell(i) == null) //{ // row.CreateCell(i).SetCellValue(data); //} //else //{ // row.GetCell(i).SetCellValue(data); //} } } workbook.Write(stm); } catch (Exception e) { Logger.Error(e.ToString()); #if DEBUG throw; #else return false; #endif } return true; } /// /// The SaveWaveByMatlab. /// /// The stm. /// The pkg. /// The . public static Boolean SaveWaveByMatlab(Stream stm, WfmPack pkg) => SaveWaveByText(stm, pkg, (x, y) => x.ToString("E") + " " + String.Join(" ", y.Select(o => o.ToString("G")))); /// /// The SaveWaveByText. /// /// The stm. /// The pkg. /// The cbfunc. /// The . public static Boolean SaveWaveByText(Stream stm, WfmPack pkg, Func cbfunc, TxtFormat wfmtxtformat = TxtFormat.UTF8) { try { using StreamWriter sw = new(stm, GetEncoding(wfmtxtformat)); Int32 length = pkg.Buffer.GetLength(1); Int32 wfmcnt = pkg.Buffer.GetLength(0); Double sp = pkg.Properties.TmbScale.Value * Constants.VIS_XDIVS_NUM / length; Double pos0 = pkg.Properties.TmbPosition.Index; Double time; Double[] ampls = new Double[wfmcnt]; var header = $"Ampl({pkg.Properties.ChnlUnit.Prefix.ToPfxString()}{pkg.Properties.ChnlUnit.Name})"; for (Int32 i = 1; i < wfmcnt; i++) { header = header + ", " + header; } header = $"Time({pkg.Properties.TmbUnit.Prefix.ToPfxString()}{pkg.Properties.TmbUnit.Name}), " + header; sw.WriteLine(header); for (Int32 j = 0; j < length; j++) { time = (j - pos0) * sp + pkg.Properties.TrigErrorTime; for (Int32 i = 0; i < wfmcnt; i++) { ampls[i] = pkg.Buffer[i, j]; } sw.WriteLine(cbfunc(time, ampls)); } } catch (Exception e) { Logger.Error(e.ToString()); #if DEBUG throw; #else return false; #endif } return true; } /// /// The SaveWaveByTSV. /// /// The stm. /// The pkg. /// The . public static Boolean SaveWaveByTSV(Stream stm, WfmPack pkg) => SaveWaveByText(stm, pkg, (x, y) => x.ToString("E") + "\t" + String.Join("\t", y.Select(o => o.ToString("G")))); /// /// The SaveWaveByTxt. /// /// The stm. /// The pkg. /// The . public static Boolean SaveWaveByTxt(Stream stm, WfmPack pkg, TxtFormat fotmat) => SaveWaveByText(stm, pkg, (x, y) => x.ToString("E") + "," + String.Join(",", y.Select(o => o.ToString("G"))), fotmat); /// /// The SaveWaveform. /// /// The fullpath. /// The wf. /// The id. /// The . public static Boolean SaveWaveform(String fullpath, WfmFormat wf, ChannelId id, TxtFormat wfmtxtfotmat = TxtFormat.UTF8) { var path = Path.GetDirectoryName(fullpath); var file = Path.GetFileName(fullpath); if (String.IsNullOrEmpty(file)) { return false; } if (path?.Length == 0) { path = Directory.GetCurrentDirectory(); } return SaveWaveform(path!, file, wf, id, false, wfmtxtfotmat); } /// /// The SaveWaveform. /// /// The path. /// The name. /// The wf. /// The id. /// The postfix. /// The . public static Boolean SaveWaveform(String path, String name, WfmFormat wf, ChannelId id, Boolean postfix, TxtFormat wfmtxtfotmat = TxtFormat.UTF8) { if (DsoModel.Default.TryGetChannel(id, out var cm) && cm.Pack is not null) { //if (cm.Pack.Properties.Version != "U2.0") // return false; if (!Directory.Exists(path)) { Directory.CreateDirectory(path); if (!Directory.Exists(path)) { Logger.Error($"Path does not exist: '{path}'"); return false; } } String fullfilename = path + "\\" + name + (postfix ? GetDateTimeString() : "") + "." + wf.GetAlias(); if (File.Exists(fullfilename)) { if (!StrongTip.Default.Show(MsgTipId.Warning, MsgTipId.FileExisted, MessageType.Warning)) { return false; } File.Delete(fullfilename); } using var fs = new FileStream(fullfilename, FileMode.OpenOrCreate, FileAccess.Write); switch (wf) { case WfmFormat.Binary: return FilePrsnt.SaveWaveByBin(fs, cm.Pack); case WfmFormat.Text: return FilePrsnt.SaveWaveByTxt(fs, cm.Pack, wfmtxtfotmat); case WfmFormat.Matlab: return FilePrsnt.SaveWaveByMatlab(fs, cm.Pack); case WfmFormat.Excel: return FilePrsnt.SaveWaveByExcel(fs, cm.Pack); case WfmFormat.CSV: return FilePrsnt.SaveWaveByCSV(fs, cm.Pack); case WfmFormat.TSV: return FilePrsnt.SaveWaveByTSV(fs, cm.Pack); case WfmFormat.WFM: case WfmFormat.HDF5: default: WeakTip.Default.Write("WfmSave", MsgTipId.UnSupportedFormat); return false; } // return wf switch // { // WfmFormat.Binary => // FilePrsnt.SaveWaveByBin(fs, cm.Pack), // WfmFormat.Text => // FilePrsnt.SaveWaveByTxt(fs, cm.Pack, wfmtxtfotmat), // WfmFormat.Excel => // FilePrsnt.SaveWaveByExcel(fs, cm.Pack), // WfmFormat.Matlab => // FilePrsnt.SaveWaveByMatlab(fs, cm.Pack), // WfmFormat.CSV => // FilePrsnt.SaveWaveByCSV(fs, cm.Pack), // WfmFormat.TSV => // FilePrsnt.SaveWaveByTSV(fs, cm.Pack), // _ => //#if DEBUG // throw new NotImplementedException(), //#else // //Logger.Error($"{nameof(WfmFormat)} '{nameof(wf)}' = {wf}"), // throw new NotImplementedException() //#endif // }; } return false; } /// /// The MakeDefaultFileName. /// /// The path. /// The ext. /// The . public String MakeDefaultFileName(String path, String ext) { var result = new DirectoryInfo(path) .GetFiles($"*{ext}", SearchOption.TopDirectoryOnly) .Where(x => Regex.IsMatch(x.Name, $"^{DefaultPrefixName}[0-9]{"{3}"}{ext}$", RegexOptions.IgnoreCase)); return DefaultPrefixName + String.Format("{0:D3}", result.Count()); } } }