using Common; using Common.Helpers; using CommunityToolkit.Mvvm.ComponentModel; using CommunityToolkit.Mvvm.Input; using MultiTerm.Core.Types; using MultiTerm.Protocols.Model; using System.Collections.ObjectModel; using System.Text; namespace MultiTerm.Core.ViewModel; public partial class CommunicationDataViewModel : ObservableObject, ICommunicationDataViewModel { private readonly IContext uiContext; private int dataCharacterCount = 0; private List? listOfPreviousCharacters = null; #region ICommunicationDataViewModel Implementation [ObservableProperty] private ObservableCollection data = new(); [ObservableProperty] private string dataAsString = string.Empty; [ObservableProperty] private ObservableCollection? selected = new(); [ObservableProperty] NewlineSeparatorType newlineSeparator = NewlineSeparatorType.None; #endregion public CommunicationDataViewModel(IContext context) { this.uiContext = context; // TEMP //{ // //string exampleData = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Pellentesque elit eget gravida cum sociis natoque penatibus et magnis. Purus sit amet volutpat consequat mauris nunc congue nisi vitae. Id ornare arcu odio ut sem. Neque ornare aenean euismod elementum nisi quis eleifend. Faucibus vitae aliquet nec ullamcorper sit. Fermentum iaculis eu non diam phasellus vestibulum lorem sed risus. Pellentesque nec nam aliquam sem et tortor consequat id porta. Diam sollicitudin tempor id eu nisl. Fames ac turpis egestas sed tempus urna et. Commodo odio aenean sed adipiscing diam donec adipiscing tristique risus. Id aliquet lectus proin nibh nisl condimentum id. Dolor sit amet consectetur adipiscing elit duis. Sed vulputate odio ut enim blandit. Neque convallis a cras semper auctor neque vitae.\r\n\r\nLacus laoreet non curabitur gravida arcu ac tortor. Volutpat maecenas volutpat blandit aliquam. Neque laoreet suspendisse interdum consectetur. Tincidunt augue interdum velit euismod in pellentesque massa placerat. Magna fringilla urna porttitor rhoncus dolor purus non enim praesent. Fermentum leo vel orci porta non pulvinar neque laoreet suspendisse. Scelerisque viverra mauris in aliquam sem fringilla. Nec feugiat nisl pretium fusce id velit ut. Urna cursus eget nunc scelerisque viverra mauris. Condimentum mattis pellentesque id nibh tortor id aliquet. Enim sed faucibus turpis in eu. Adipiscing elit pellentesque habitant morbi tristique. A pellentesque sit amet porttitor eget dolor morbi non arcu. Amet commodo nulla facilisi nullam vehicula ipsum a arcu. Hac habitasse platea dictumst vestibulum rhoncus est pellentesque elit ullamcorper. Curabitur vitae nunc sed velit dignissim sodales ut. Malesuada fames ac turpis egestas maecenas pharetra. Tellus pellentesque eu tincidunt tortor aliquam.\r\n\r\nVitae proin sagittis nisl rhoncus mattis rhoncus urna neque viverra. Eget mi proin sed libero enim sed faucibus. Commodo nulla facilisi nullam vehicula ipsum. Proin libero nunc consequat interdum varius sit amet mattis vulputate. Morbi tristique senectus et netus. Feugiat scelerisque varius morbi enim nunc. Nulla aliquet enim tortor at auctor urna nunc. Non pulvinar neque laoreet suspendisse interdum consectetur libero id. Tellus orci ac auctor augue mauris augue neque gravida in. In egestas erat imperdiet sed euismod. Amet volutpat consequat mauris nunc congue nisi. Massa eget egestas purus viverra accumsan in. Eget duis at tellus at. Mi sit amet mauris commodo quis imperdiet. Nibh mauris cursus mattis molestie a iaculis at.\r\n\r\nNetus et malesuada fames ac turpis. Sit amet dictum sit amet justo donec. Euismod quis viverra nibh cras pulvinar mattis. Sit amet commodo nulla facilisi nullam vehicula ipsum a arcu. Scelerisque felis imperdiet proin fermentum. Ac tincidunt vitae semper quis lectus nulla at. Sit amet commodo nulla facilisi nullam vehicula. Enim lobortis scelerisque fermentum dui faucibus in ornare quam. Quam id leo in vitae turpis massa sed. Quam quisque id diam vel quam. A condimentum vitae sapien pellentesque. Neque aliquam vestibulum morbi blandit cursus risus at. Velit laoreet id donec ultrices tincidunt arcu non sodales neque. Tempus imperdiet nulla malesuada pellentesque elit eget gravida cum sociis. Egestas tellus rutrum tellus pellentesque eu tincidunt tortor. Nec feugiat in fermentum posuere. Dui accumsan sit amet nulla. Lacus viverra vitae congue eu consequat ac felis. Etiam tempor orci eu lobortis. Fermentum leo vel orci porta non pulvinar."; // string exampleData = "\r\nUnicode Latin Letter D: \u018A\n--------------------------------------------------------------\r\nSPLITFLAP\r\n--------------------------------------------------------------\r\nMcuShell ; Group of McuShell commands\r\n help|status ; Print help or status information\r\nSplitFlap ; Group of McuRTOS commands\r\n help ; Print help or status information\r\n setId ; sets the position (setupId) of the sf and its id (hwId)\r\n initAll ; init all Splitflaps\r\n Display ; displays as many chars of the string as sf are available\r\n addId ; add new hwId with offset\r\nMcuRTOS ; Group of McuRTOS commands\r\n help|status ; Print help or status information\r\n tasklist ; Print tasklist\r\nMcuFlash ; Group of flash ini commands\r\n help|status ; Print help or status information\r\n dump ; Dump memory data\r\n erase ; Erase memory at address\r\nini ; Group of flash ini commands\r\n help|status ; Print help or status information\r\n dump ; Dump data information\r\n erase ; Erase data information\r\nMcuMinINI ; Group of McuMinINI commands\r\n help|status ; Print help or status information\r\n read ; Read a key from a section in a file\r\n write ; Write a key with value to a section in a file\r\n delkey ; Delete a key in a section of file\r\n delsec ; Delete a section in a file\r\nnvmc ; Group of NVMC commands\r\n help|status ; Print help or status information\r\n flags ; Set flags\r\nrs ; Group of RS-485 commands\r\n help|status ; Print help or status information\r\n addr ; Set RS-485 address\r\n send ; Send a text to the RS-485 bus\r\n sendcmd ; Send a shell command to the RS-485 address and check response\r\n log on|off ; Log RS-485 bus activity to McuLog\r\nMcuUart485 ; Group of RS-485 commands\r\n help|status ; Print help or status information\r\n clear ; Clear UART ISR flags\r\n\r\nCMD>"; // //string exampleData = "This is some example Text\nSecond line\nNow a very long line: Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua."; // int counter = 0; // int lineNumber = 1; // //List listOfChars = new(); // foreach (var dataByte in exampleData) // { // if(++counter > 100 || dataByte == '\n') // { // //this.ReceivedData.Add(); // //listOfChars = new List(); // counter = 0; // lineNumber += 1; // } // var extdChar = new ExtendedChar(dataByte); // //listOfChars.Add(extdChar); // this.ReceivedData.Add(new DataViewModel(extdChar, lineNumber)); // } //} } public void HandleNewData(IEnumerable newRawData) { // update collection and string, invoke ui thread if necessary ContextHelpers.InvokeIfNecessary(this.uiContext, (Action)delegate { this.DataAsString = InsertNewNewCharactersIntoCollection(this.Data, this.DataAsString, ref this.dataCharacterCount, ref this.listOfPreviousCharacters, this.NewlineSeparator, newRawData); }); } /// /// After changing the newline separator, the data needs to be reordered. /// partial void OnNewlineSeparatorChanged(NewlineSeparatorType value) { // update collection, invoke ui thread if necessary ContextHelpers.InvokeIfNecessary(this.uiContext, (Action)delegate { var reorderedCollection = ReorderCollection(this.Data, value); this.Data = reorderedCollection.Item1; this.DataAsString = reorderedCollection.Item2; }); } [RelayCommand] public void Clear() { // update collection and string, invoke ui thread if necessary ContextHelpers.InvokeIfNecessary(this.uiContext, (Action)delegate { this.DataAsString = string.Empty; this.Data.Clear(); }); } #region Collection Manipulation /// /// Function that reorders a given collection with item type using the given . /// Reordered collection is returned, but LineIdentifier is also overwritten in the parameter. /// /// items in this collection will be reordered /// separator between lines /// reordered collection and string private static Tuple, string> ReorderCollection(ObservableCollection currentCollection, NewlineSeparatorType newlineSeparatorType) { ObservableCollection newCollection = new(); StringBuilder stringBuilder = new(); // local vars int lineCounter = 0; List? previousBytes = null; // iterate through items foreach (ByteDataViewModel item in currentCollection) { item.LineIdentifier = lineCounter; newCollection.Add(item); stringBuilder.Append(item.DisplayStringChar); switch (ShouldIntroduceNewlineAfterThisByte(item.Byte, previousBytes, newlineSeparatorType)) { case ShouldIntroduceNewlineAfterThisByteResult.NoNewline: // a decision could be made, previousBytes can be cleared if (previousBytes != null) { previousBytes = null; } // nothing to do break; case ShouldIntroduceNewlineAfterThisByteResult.IntroduceNewline: // a decision could be made, previousBytes can be cleared if (previousBytes != null) { previousBytes = null; } // increase line count lineCounter++; // append line in string stringBuilder.AppendLine(); break; case ShouldIntroduceNewlineAfterThisByteResult.RequiresMoreCharacters: // first time that more bytes are required => create new list previousBytes ??= new List(); // add current byte to list previousBytes.Add(item.Byte); break; default: throw new Exception($"'{nameof(ReorderCollection)}()' failed because of error when checking if a newline should be introduced."); } } return Tuple.Create(newCollection, stringBuilder.ToString()); } /// /// Function that handles a collection of new bytes that should end up in the collection . /// In case a new line is required, according to the given , it is automatically introduced. /// Following parameters need to be referenced and stored outside: and . /// /// collection to add the bytes to /// collection as string /// current line count /// list of previous bytes, newest at the last position of the list, null if nothing is stored /// separator between seperate lines /// bytes to add to the /// string representation of data /// in case of any error private static string InsertNewNewCharactersIntoCollection( ObservableCollection dataCollection, string dataCollectionAsString, ref int collectionLineCounter, ref List? previousBytes, NewlineSeparatorType newlineSeparatorType, IEnumerable newBytes) { StringBuilder stringBuilder = new(); stringBuilder.Append(dataCollectionAsString); // go through every byte foreach (ExtendedByte newByte in newBytes) { // add to collection and string with the current counter, invoking UI context if necssary var currentLineCounter = collectionLineCounter; dataCollection.Add(new ByteDataViewModel(newByte, currentLineCounter)); stringBuilder.Append(newByte.ToCharacterString()); switch (ShouldIntroduceNewlineAfterThisByte(newByte.Byte, previousBytes, newlineSeparatorType)) { case ShouldIntroduceNewlineAfterThisByteResult.NoNewline: // a decision could be made, previousBytes can be cleared if (previousBytes != null) { previousBytes = null; } // nothing to do break; case ShouldIntroduceNewlineAfterThisByteResult.IntroduceNewline: // a decision could be made, previousBytes can be cleared if (previousBytes != null) { previousBytes = null; } // increase line count collectionLineCounter++; // append line in string stringBuilder.AppendLine(); break; case ShouldIntroduceNewlineAfterThisByteResult.RequiresMoreCharacters: // first time that more bytes are required => create new list previousBytes ??= new List(); // add current byte to list previousBytes.Add(newByte.Byte); break; default: throw new Exception($"'{nameof(InsertNewNewCharactersIntoCollection)}()' failed because of error when checking if a newline should be introduced."); } } return stringBuilder.ToString(); } /// /// Result type for /// public enum ShouldIntroduceNewlineAfterThisByteResult { /// /// No newline is required. /// NoNewline, /// /// A newline shall be introduced after this byte. /// IntroduceNewline, /// /// Following characters are required to finalize result wether a newline shall be introduced or not. /// RequiresMoreCharacters } /// /// Function to check wether a newline shall be introduced after the given . /// Since some newline sequences will require multiple bytes in correct order, a more complex handling is required, which is possible using this function. /// /// the current dataByte in the collection (or a single byte) /// list of previous bytes, newest at the last position of the list, null if not required /// separator type /// enum result of type /// if the handling for the is not implemented private static ShouldIntroduceNewlineAfterThisByteResult ShouldIntroduceNewlineAfterThisByte(byte dataByte, List? previousBytes, NewlineSeparatorType newlineSeparatorType) { var result = ShouldIntroduceNewlineAfterThisByteResult.NoNewline; switch (newlineSeparatorType) { case NewlineSeparatorType.None: break; case NewlineSeparatorType.CR: if (dataByte == (byte)'\r') { result = ShouldIntroduceNewlineAfterThisByteResult.IntroduceNewline; } break; case NewlineSeparatorType.LF: if (dataByte == (byte)'\n') { result = ShouldIntroduceNewlineAfterThisByteResult.IntroduceNewline; } break; case NewlineSeparatorType.CR_LF: if (dataByte == (byte)'\r') { result = ShouldIntroduceNewlineAfterThisByteResult.RequiresMoreCharacters; } if (dataByte == (byte)'\n') { if (previousBytes != null && previousBytes.Last() == (byte)'\r') { result = ShouldIntroduceNewlineAfterThisByteResult.IntroduceNewline; } } break; default: throw new NotImplementedException($"'{nameof(ShouldIntroduceNewlineAfterThisByte)}()' does not implement handling for {nameof(NewlineSeparatorType)} {newlineSeparatorType}"); } return result; } #endregion }