forked from Serial-Studio/Serial-Studio
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathConsole.cpp
More file actions
650 lines (572 loc) · 16.8 KB
/
Console.cpp
File metadata and controls
650 lines (572 loc) · 16.8 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
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
/*
* Copyright (c) 2020-2022 Alex Spataru <https://github.com/alex-spataru>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
#include <QFile>
#include <QPrinter>
#include <QDateTime>
#include <QFileDialog>
#include <QPrintDialog>
#include <QTextDocument>
#include <IO/Manager.h>
#include <IO/Console.h>
#include <Misc/Utilities.h>
#include <Misc/TimerEvents.h>
/**
* Generates a hexdump of the given data
*/
static QString HexDump(const char *data, const size_t size)
{
char str[4096] = "";
char ascii[17];
size_t i, j;
ascii[16] = '\0';
for (i = 0; i < size; ++i)
{
sprintf(str + strlen(str), "%02X ", static_cast<quint8>(data[i]));
if (data[i] >= ' ' && data[i] <= '~')
ascii[i % 16] = data[i];
else
ascii[i % 16] = '.';
if ((i + 1) % 8 == 0 || i + 1 == size)
{
sprintf(str + strlen(str), " ");
if ((i + 1) % 16 == 0)
sprintf(str + strlen(str), "| %s \n", ascii);
else if (i + 1 == size)
{
ascii[(i + 1) % 16] = '\0';
if ((i + 1) % 16 <= 8)
sprintf(str + strlen(str), " ");
for (j = (i + 1) % 16; j < 16; ++j)
sprintf(str + strlen(str), " ");
sprintf(str + strlen(str), "| %s \n", ascii);
}
}
}
return QString(str);
}
/**
* Constructor function
*/
IO::Console::Console()
: m_dataMode(DataMode::DataUTF8)
, m_lineEnding(LineEnding::NoLineEnding)
, m_displayMode(DisplayMode::DisplayPlainText)
, m_historyItem(0)
, m_echo(false)
, m_autoscroll(true)
, m_showTimestamp(false)
, m_isStartingLine(true)
{
// Clear buffer & reserve memory
clear();
// Read received data automatically
auto dm = &Manager::instance();
connect(dm, &Manager::dataSent, this, &IO::Console::onDataSent);
connect(dm, &Manager::dataReceived, this, &IO::Console::onDataReceived);
}
/**
* Returns the only instance of the class
*/
IO::Console &IO::Console::instance()
{
static Console singleton;
return singleton;
}
/**
* Returns @c true if the console shall display the commands that the user has sent
* to the serial/network device.
*/
bool IO::Console::echo() const
{
return m_echo;
}
/**
* Returns @c true if the vertical position of the console display shall be automatically
* moved to show latest data.
*/
bool IO::Console::autoscroll() const
{
return m_autoscroll;
}
/**
* Returns @c true if data buffer contains information that the user can export.
*/
bool IO::Console::saveAvailable() const
{
return m_textBuffer.length() > 0;
}
/**
* Returns @c true if a timestamp should be shown before each displayed data block.
*/
bool IO::Console::showTimestamp() const
{
return m_showTimestamp;
}
/**
* Returns the type of data that the user inputs to the console. There are two possible
* values:
* - @c DataMode::DataUTF8 the user is sending data formated in the UTF-8 codec.
* - @c DataMode::DataHexadecimal the user is sending binary data represented in
* hexadecimal format, we must do a conversion to obtain
* and send the appropiate binary data to the target
* device.
*/
IO::Console::DataMode IO::Console::dataMode() const
{
return m_dataMode;
}
/**
* Returns the line ending character that is added to each datablock sent by the user.
* Possible values are:
* - @c LineEnding::NoLineEnding leave data as-it-is
* - @c LineEnding::NewLine, add '\n' to the data sent by the user
* - @c LineEnding::CarriageReturn, add '\r' to the data sent by the user
* - @c LineEnding::BothNewLineAndCarriageReturn add '\r\n' to the data sent by the user
*/
IO::Console::LineEnding IO::Console::lineEnding() const
{
return m_lineEnding;
}
/**
* Returns the display format of the console. Posible values are:
* - @c DisplayMode::DisplayPlainText display incoming data as an UTF-8 stream
* - @c DisplayMode::DisplayHexadecimal display incoming data in hexadecimal format
*/
IO::Console::DisplayMode IO::Console::displayMode() const
{
return m_displayMode;
}
/**
* Returns the current command history string selected by the user.
*
* @note the user can navigate through sent commands using the Up/Down keys on the
* keyboard. This behaviour is managed by the @c historyUp() & @c historyDown()
* functions.
*/
QString IO::Console::currentHistoryString() const
{
if (m_historyItem < m_historyItems.count() && m_historyItem >= 0)
return m_historyItems.at(m_historyItem);
return "";
}
/**
* Returns a list with the available data (sending) modes. This list must be synchronized
* with the order of the @c DataMode enums.
*/
StringList IO::Console::dataModes() const
{
StringList list;
list.append(tr("ASCII"));
list.append(tr("HEX"));
return list;
}
/**
* Returns a list with the available line endings options. This list must be synchronized
* with the order of the @c LineEnding enums.
*/
StringList IO::Console::lineEndings() const
{
StringList list;
list.append(tr("No line ending"));
list.append(tr("New line"));
list.append(tr("Carriage return"));
list.append(tr("NL + CR"));
return list;
}
/**
* Returns a list with the available console display modes. This list must be synchronized
* with the order of the @c DisplayMode enums.
*/
StringList IO::Console::displayModes() const
{
StringList list;
list.append(tr("Plain text"));
list.append(tr("Hexadecimal"));
return list;
}
/**
* Validates the given @a text and adds space to display the text in a byte-oriented view
*/
QString IO::Console::formatUserHex(const QString &text)
{
// Remove spaces & stuff
auto data = text.simplified();
data = data.replace(" ", "");
// Convert to hex string with spaces between bytes
QString str;
for (int i = 0; i < data.length(); ++i)
{
str.append(data.at(i));
if ((i + 1) % 2 == 0 && i > 0)
str.append(" ");
}
// Chop last space
while (str.endsWith(" "))
str.chop(1);
// Return string
return str;
}
/**
* Allows the user to export the information displayed on the console
*/
void IO::Console::save()
{
// No data buffer received, abort
if (!saveAvailable())
return;
// Get file name
auto path
= QFileDialog::getSaveFileName(Q_NULLPTR, tr("Export console data"),
QDir::homePath(), tr("Text files") + " (*.txt)");
// Create file
if (!path.isEmpty())
{
QFile file(path);
if (file.open(QFile::WriteOnly))
{
file.write(m_textBuffer.toUtf8());
file.close();
Misc::Utilities::revealFile(path);
}
else
Misc::Utilities::showMessageBox(tr("File save error"), file.errorString());
}
}
/**
* Deletes all the text displayed by the current QML text document
*/
void IO::Console::clear()
{
m_textBuffer.clear();
m_textBuffer.reserve(10 * 1000);
m_isStartingLine = true;
Q_EMIT dataReceived();
}
/**
* Comamnds sent by the user are stored in a @c StringList, in which the first items
* are the oldest commands.
*
* The user can navigate the list using the up/down keys. This function allows the user
* to navigate the list from most recent command to oldest command.
*/
void IO::Console::historyUp()
{
if (m_historyItem > 0)
{
--m_historyItem;
Q_EMIT historyItemChanged();
}
}
/**
* Comamnds sent by the user are stored in a @c StringList, in which the first items
* are the oldest commands.
*
* The user can navigate the list using the up/down keys. This function allows the user
* to navigate the list from oldst command to most recent command.
*/
void IO::Console::historyDown()
{
if (m_historyItem < m_historyItems.count() - 1)
{
++m_historyItem;
Q_EMIT historyItemChanged();
}
}
/**
* Sends the given @a data to the currently connected device using the options specified
* by the user with the rest of the functions of this class.
*
* @note @c data is added to the history of sent commands, regardless if the data writing
* was successfull or not.
*/
void IO::Console::send(const QString &data)
{
// Check conditions
if (data.isEmpty() || !Manager::instance().connected())
return;
// Add user command to history
addToHistory(data);
// Convert data to byte array
QByteArray bin;
if (dataMode() == DataMode::DataHexadecimal)
bin = hexToBytes(data);
else
bin = data.toUtf8();
// Add EOL character
switch (lineEnding())
{
case LineEnding::NoLineEnding:
break;
case LineEnding::NewLine:
bin.append("\n");
break;
case LineEnding::CarriageReturn:
bin.append("\r");
break;
case LineEnding::BothNewLineAndCarriageReturn:
bin.append("\r");
bin.append("\n");
break;
}
// Write data to device
Manager::instance().writeData(bin);
}
/**
* Enables or disables displaying sent data in the console screen. See @c echo() for more
* information.
*/
void IO::Console::setEcho(const bool enabled)
{
m_echo = enabled;
Q_EMIT echoChanged();
}
/**
* Creates a text document with current console output & prints it using native
* system libraries/toolkits.
*
* @param fontFamily the font family to use to render the text document
*/
void IO::Console::print(const QString &fontFamily)
{
// Get document font (specified by QML ui)
QFont font;
font.setPointSize(10);
font.setFamily(fontFamily);
// Create text document
QTextDocument document;
document.setDefaultFont(font);
document.setPlainText(m_textBuffer);
// Create printer object
QPrinter printer(QPrinter::PrinterResolution);
printer.setFullPage(true);
printer.setDocName(qApp->applicationName());
printer.setPageOrientation(QPageLayout::Portrait);
// Show print dialog
QPrintDialog printDialog(&printer, Q_NULLPTR);
if (printDialog.exec() == QDialog::Accepted)
{
document.print(&printer);
}
}
/**
* Enables/disables displaying a timestamp of each received data block.
*/
void IO::Console::setShowTimestamp(const bool enabled)
{
if (showTimestamp() != enabled)
{
m_showTimestamp = enabled;
Q_EMIT showTimestampChanged();
}
}
/**
* Enables/disables autoscrolling of the console text.
*/
void IO::Console::setAutoscroll(const bool enabled)
{
if (autoscroll() != enabled)
{
m_autoscroll = enabled;
Q_EMIT autoscrollChanged();
}
}
/**
* Changes the data mode for user commands. See @c dataMode() for more information.
*/
void IO::Console::setDataMode(const IO::Console::DataMode &mode)
{
m_dataMode = mode;
Q_EMIT dataModeChanged();
}
/**
* Changes line ending mode for sent user commands. See @c lineEnding() for more
* information.
*/
void IO::Console::setLineEnding(const IO::Console::LineEnding &mode)
{
m_lineEnding = mode;
Q_EMIT lineEndingChanged();
}
/**
* Changes the display mode of the console. See @c displayMode() for more information.
*/
void IO::Console::setDisplayMode(const IO::Console::DisplayMode &mode)
{
m_displayMode = mode;
Q_EMIT displayModeChanged();
}
/**
* Inserts the given @a string into the list of lines of the console, if @a addTimestamp
* is set to @c true, an timestamp is added for each line.
*/
void IO::Console::append(const QString &string, const bool addTimestamp)
{
// Abort on empty strings
if (string.isEmpty())
return;
// Only use \n as line separator
auto data = string;
data = data.replace("\r\n", "\n");
data = data.replace("\r", "\n");
// Get timestamp
QString timestamp;
if (addTimestamp)
{
QDateTime dateTime = QDateTime::currentDateTime();
timestamp = dateTime.toString("HH:mm:ss.zzz -> ");
}
// Initialize final string
QString processedString;
processedString.reserve(data.length() + timestamp.length());
// Create list with lines (keep separators)
StringList tokens;
QString currentToken;
for (int i = 0; i < data.length(); ++i)
{
if (data.at(i) == '\n')
{
tokens.append(currentToken);
tokens.append("\n");
currentToken.clear();
}
else
currentToken += data.at(i);
}
// Add last item to list
if (!currentToken.isEmpty())
tokens.append(currentToken);
// Process lines
while (!tokens.isEmpty())
{
if (m_isStartingLine)
processedString.append(timestamp);
auto token = tokens.first();
processedString.append(token);
m_isStartingLine = (token == "\n");
tokens.removeFirst();
}
// Add data to saved text buffer
m_textBuffer.append(processedString);
// Update UI
Q_EMIT dataReceived();
Q_EMIT stringReceived(processedString);
}
/**
* Displays the given @a data in the console. @c QByteArray to ~@c QString conversion is
* done by the @c dataToString() function, which displays incoming data either in UTF-8
* or in hexadecimal mode.
*/
void IO::Console::onDataSent(const QByteArray &data)
{
if (echo())
append(dataToString(data) + "\n", showTimestamp());
}
/**
* Displays the given @a data in the console
*/
void IO::Console::onDataReceived(const QByteArray &data)
{
append(dataToString(data), showTimestamp());
}
/**
* Registers the given @a command to the list of sent commands.
*/
void IO::Console::addToHistory(const QString &command)
{
// Remove old commands from history
while (m_historyItems.count() > 100)
m_historyItems.removeFirst();
// Register command
m_historyItems.append(command);
m_historyItem = m_historyItems.count();
Q_EMIT historyItemChanged();
}
/**
* Converts the given @a data in HEX format into real binary data.
*/
QByteArray IO::Console::hexToBytes(const QString &data)
{
QString withoutSpaces = data;
withoutSpaces.replace(" ", "");
QByteArray array;
for (int i = 0; i < withoutSpaces.length(); i += 2)
{
auto chr1 = withoutSpaces.at(i);
auto chr2 = withoutSpaces.at(i + 1);
auto byte = QString("%1%2").arg(chr1, chr2).toInt(Q_NULLPTR, 16);
array.append(byte);
}
return array;
}
/**
* Converts the given @a data to a string according to the console display mode set by the
* user.
*/
QString IO::Console::dataToString(const QByteArray &data)
{
switch (displayMode())
{
case DisplayMode::DisplayPlainText:
return plainTextStr(data);
break;
case DisplayMode::DisplayHexadecimal:
return hexadecimalStr(data);
break;
default:
return "";
break;
}
}
/**
* Converts the given @a data into an UTF-8 string
*/
QString IO::Console::plainTextStr(const QByteArray &data)
{
QString str = QString::fromUtf8(data);
if (str.toUtf8() != data)
str = QString::fromLatin1(data);
return str;
}
/**
* Converts the given @a data into a HEX representation string.
*/
QString IO::Console::hexadecimalStr(const QByteArray &data)
{
// Remove line breaks from data
QByteArray copy = data;
// Convert data to string with dump every ~80 chars
QString str;
const int characters = 80;
for (int i = 0; i < copy.length(); ++i)
{
QByteArray line;
for (int j = 0; j < qMin(characters, copy.length() - i); ++j)
line.append(copy.at(i + j));
i += characters;
str.append(HexDump(line.data(), line.size()));
}
// Return string
return str;
}
#ifdef SERIAL_STUDIO_INCLUDE_MOC
# include "moc_Console.cpp"
#endif